【问题标题】:Where to put addEventListener so it doesn't fire multiple times在哪里放置 addEventListener 所以它不会触发多次
【发布时间】:2020-07-27 08:21:54
【问题描述】:

我有一个 Javascript 文件,它用圆圈绘制画布。如果我点击一个圆圈,颜色必须改变。这可行,但 eventHandler 一键触发多次。因此,该程序滞后很多。我该如何改进?

var cvs = document.getElementById("canvas");

var ctx = cvs.getContext("2d");

class Circle {
  constructor(x, y, radius, color) {
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.color = color;
  }

  draw = function() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
    ctx.strokeStyle = this.color;
    ctx.stroke();
  };

  update = function() {
    cvs.addEventListener("click", function(e) {
      var mousePosition = this.getMousePosition(e);
      this.checkForCollision(mousePosition);
    }.bind(this));
    this.draw();
  };

  getMousePosition = function(e) {
    var cRect = cvs.getBoundingClientRect();
    var canvasX = Math.round(e.clientX - cRect.left);
    var canvasY = Math.round(e.clientY - cRect.top);
    return {
      x: canvasX,
      y: canvasY
    }
  }

  checkForCollision = function(mPos) {
    if (mPos.x < this.x + this.radius && mPos.x > this.x - this.radius && mPos.y < this.y + this.radius && mPos.y > this.y - this.radius) {
      this.color = "blue";
    }
  }
}

var circles = [];
for (x = 0; x < 8; x++) {
  for (y = 0; y < 8; y++) {
    circles.push(new Circle(x * 100 + 30, y * 100 + 30, 20, "red"));
  }
}

function playGame() {
  requestAnimationFrame(playGame);
  ctx.clearRect(0, 0, 2000, 2000);
  circles.forEach(circle => circle.update());
}

playGame();
&lt;canvas id="canvas"&gt;&lt;/canvas&gt;

【问题讨论】:

  • 您在每个绘制周期都添加一个新的点击事件,这个事件加起来很快。尝试将addEventListener 移出绘制/更新周期。
  • 尝试在构造函数中只添加一次
  • @TimMG 既然您已经在var circles = []; 中声明了一个圆数组,那么您可以做的是只为点击附加一个事件侦听器,当您检测到点击时,遍历所有 Circle 对象数组以查看发生单击的鼠标位置是否在当前圆圈内。

标签: javascript eventhandler


【解决方案1】:

目前,由于您调用addEventListener 的位置,您正在每个绘制周期添加一个事件侦听器。如果您改为将 addEventListener 移动到圆的构造函数,则每个 Circle 对象只会附加一次(在您的情况下为 64 次):

var cvs = document.getElementById("canvas");

var ctx = cvs.getContext("2d");

class Circle {
    constructor(x, y, radius, color) {
        this.x = x;
        this.y = y;
        this.radius = radius;
        this.color = color;
        cvs.addEventListener("click", function (e) {
            var mousePosition = this.getMousePosition(e);
            this.checkForCollision(mousePosition);
            console.log('Click detected!');
        }.bind(this));
    }

    draw = function () {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
        ctx.strokeStyle = this.color;
        ctx.stroke();
    };

    update = function () {
        this.draw();
    };

    getMousePosition = function (e) {
        var cRect = cvs.getBoundingClientRect();
        var canvasX = Math.round(e.clientX - cRect.left);
        var canvasY = Math.round(e.clientY - cRect.top);
        return {
            x: canvasX,
            y: canvasY
        }
    }

    checkForCollision = function (mPos) {
        if (mPos.x < this.x + this.radius && mPos.x > this.x - this.radius && mPos.y < this.y + this.radius && mPos.y > this.y - this.radius) {
            this.color = "blue";
        }
    }
}

var circles = [];
for(x = 0; x < 8; x++){
    for(y = 0; y < 8; y++){
        circles.push(new Circle(x * 100 + 30, y * 100 + 30, 20, "red"));
    }
}

function playGame() {
    requestAnimationFrame(playGame);
    ctx.clearRect(0, 0, 2000, 2000);
    circles.forEach(circle => circle.update());
}

playGame();
&lt;canvas id="canvas" width="1000" height="1000"&gt; &lt;/canvas&gt;

如果您只想在每次点击时触发一次点击事件,请将 getMousePosition 函数移到您的 Circle 类之外并循环遍历圆数组并检查点击是否在其边界内:

var cvs = document.getElementById("canvas");

var ctx = cvs.getContext("2d");

class Circle {
    constructor(x, y, radius, color) {
        this.x = x;
        this.y = y;
        this.radius = radius;
        this.color = color;
    }

    draw = function () {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
        ctx.strokeStyle = this.color;
        ctx.stroke();
    };

    update = function () {
        this.draw();
    };

    checkForCollision = function(mPos) {
        if (mPos.x < this.x + this.radius && mPos.x > this.x - this.radius && mPos.y < this.y + this.radius && mPos.y > this.y - this.radius) {
            this.color = "blue";
            return true;
        }
        return false;
    }
}

var circles = [];
for(x = 0; x < 8; x++){
    for(y = 0; y < 8; y++){
        circles.push(new Circle(x * 100 + 30, y * 100 + 30, 20, "red"));
    }
}

function playGame() {
    requestAnimationFrame(playGame);
    ctx.clearRect(0, 0, 2000, 2000);
    circles.forEach(circle => circle.update());
}

function getMousePosition(e) {
    var cRect = cvs.getBoundingClientRect();
    var canvasX = Math.round(e.clientX - cRect.left);
    var canvasY = Math.round(e.clientY - cRect.top);
    return {
        x: canvasX,
        y: canvasY
    }
}

cvs.addEventListener("click", function (e) {
    console.log('Click detected!');
    var mousePosition = getMousePosition(e);
    circles.some(circle => {
        return circle.checkForCollision(mousePosition);
    });
});

playGame();
&lt;canvas id="canvas" width="1000" height="1000"&gt; &lt;/canvas&gt;

【讨论】:

    【解决方案2】:

    您在每个绘制周期都添加了一个新的点击事件,这个事件加起来很快。尝试将 addEventListener 移到绘制/更新周期之外。

    event bubbling 也可能导致函数多次触发。不过,这可以通过event.stopPropagation() 轻松解决。

    类外的事件监听器。

    var cvs = document.getElementById("canvas");
    
    var ctx = cvs.getContext("2d");
    
    class Circle {
        constructor(x, y, radius, color) {
            this.x = x;
            this.y = y;
            this.radius = radius;
            this.color = color;
        }
    
        draw = function () {
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
            ctx.strokeStyle = this.color;
            ctx.stroke();
        };
    
        update = function () {
            this.draw();
        };
    
        getMousePosition = function (e) {
            var cRect = cvs.getBoundingClientRect();
            var canvasX = Math.round(e.clientX - cRect.left);
            var canvasY = Math.round(e.clientY - cRect.top);
            return {
                x: canvasX,
                y: canvasY
            }
        }
    
        checkForCollision = function (mPos) {
            if (mPos.x < this.x + this.radius && mPos.x > this.x - this.radius && mPos.y < this.y + this.radius && mPos.y > this.y - this.radius) {
                this.color = "blue";
            }
        }
    }
    
    var circles = [];
    for(x = 0; x < 8; x++){
        for(y = 0; y < 8; y++){
            circles.push(new Circle(x * 100 + 30, y * 100 + 30, 20, "red"));
        }
    }
    
    cvs.addEventListener("click", function (e) {
      e.stopPropagation();
      for(const circle of circles) {
        var mousePosition = circle.getMousePosition(e);
        circle.checkForCollision(mousePosition);
      }
    });
    
    function playGame() {
        requestAnimationFrame(playGame);
        ctx.clearRect(0, 0, 2000, 2000);
        
        for(const circle of circles) {
           circle.update();
        }
    }
    
    playGame();
    canvas {
      width: 500px;
      height: 500px;
    }
    &lt;canvas id="canvas"&gt;&lt;/canvas&gt;

    构造函数中的事件监听器。

    var cvs = document.getElementById("canvas");
    
    var ctx = cvs.getContext("2d");
    
    class Circle {
        constructor(x, y, radius, color) {
            this.x = x;
            this.y = y;
            this.radius = radius;
            this.color = color;
            
            cvs.addEventListener("click", function (e) {
                e.stopPropagation()
                var mousePosition = this.getMousePosition(e);
                this.checkForCollision(mousePosition);
            }.bind(this));
        }
    
        draw = function () {
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
            ctx.strokeStyle = this.color;
            ctx.stroke();
        };
    
        update = function () {
            this.draw();
        };
    
        getMousePosition = function (e) {
            var cRect = cvs.getBoundingClientRect();
            var canvasX = Math.round(e.clientX - cRect.left);
            var canvasY = Math.round(e.clientY - cRect.top);
            return {
                x: canvasX,
                y: canvasY
            }
        }
    
        checkForCollision = function (mPos) {
            if (mPos.x < this.x + this.radius && mPos.x > this.x - this.radius && mPos.y < this.y + this.radius && mPos.y > this.y - this.radius) {
                this.color = "blue";
            }
        }
    }
    
    var circles = [];
    for(x = 0; x < 8; x++){
        for(y = 0; y < 8; y++){
            circles.push(new Circle(x * 100 + 30, y * 100 + 30, 20, "red"));
        }
    }
    
    function playGame() {
        requestAnimationFrame(playGame);
        ctx.clearRect(0, 0, 2000, 2000);
        
        for(const circle of circles) {
           circle.update();
        }
    }
    
    playGame();
    canvas {
      width: 500px;
      height: 500px;
    }
    &lt;canvas id="canvas"&gt;&lt;/canvas&gt;

    【讨论】:

    • 你为什么改变 circles.forEach(circle => circle.update());到 for 循环?
    猜你喜欢
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多