如何阻止事件监听器减慢画布动画的速度?

时间:2018-04-24 20:57:36

标签: javascript canvas event-listener

我正在制作画布动画,我刚刚开始添加事件监听器。不幸的是,当我添加一个监听器来跟踪光标的位置时,每次移动鼠标时动画都会显着减慢。如果我点击,它会完全停止。我猜这是处理太多,所以有没有办法改善动画的运行时间?这适用于Web Workers吗?

var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var c = canvas.getContext('2d');
//Variables for the blue ball
var bx = Math.random() * innerWidth;
var by = Math.random() * innerHeight;
var bbdx = 1;
var bbdy = 1;
var bRadius = 12;
//Variables for the red balls
var rx = Math.random() * innerWidth;
var ry = Math.random() * innerHeight;
var rrdx = 1;
var rrdy = 1;
var rRadius = 12;
//Mouse coordinate object
var mouse = {
  x: undefined,
  y: undefined
}

function bCircle() {
  c.beginPath();
  c.arc(bx, by, bRadius, 0, Math.PI * 2, false);
  c.strokeStyle = "white";
  c.stroke();
  c.fillStyle = "cornflowerblue";
  c.fill();
  c.closePath();

  //Ball bouncing Conditional
}

function rCircle() {
  c.beginPath();
  c.arc(rx, ry, rRadius, 0, Math.PI * 2, false);
  c.strokeStyle = "pink";
  c.stroke();
  c.fillStyle = "red";
  c.fill();
  c.closePath();
  //Ball Bouncing Conditional
}

//Interactivity function
function bClick() {
  window.addEventListener('mousemove', function(event) {
    mouse.x = event.x;
    mouse.y = event.y;
    console.log(mouse);
  });
}

function draw() {
  c.clearRect(0, 0, innerWidth, innerHeight);
  bCircle();
  rCircle();

  //bCircle Conditional
  if (bx + bRadius > innerWidth || bx - bRadius < 0) {
    bbdx = -bbdx;
  }
  //Conditional to mall the ball bounce up and down
  if (by + bRadius > innerHeight || by - bRadius < 0) {
    bbdy = -bbdy;
  }
  //Add 1 to x continously for it to move
  bx += bbdx;
  //Add 1 constantly to y for it to move up and down also
  by += bbdy;

  //rCircle Conditional
  if (rx + rRadius > innerWidth || rx - rRadius < 0) {
    rrdx = -rrdx;
  }
  if (ry + rRadius > innerHeight || ry - rRadius < 0) {
    rrdy = -rrdy;
  }
  rx += rrdx;
  ry += rrdy;

  bClick();
}

setInterval(function() {
  draw();
}, 8);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Tap-Tap</title>

  <style type="text/css">
    canvas {
      border: 1px solid black;
    }
    
    body {
      margin: 0;
      background-color: black;
    }
  </style>
</head>

<body>
  <canvas></canvas>

  <script src="ball.js" type="text/javascript"></script>

</body>

</html>

1 个答案:

答案 0 :(得分:2)

您每次调用draw()时都会减少“mousemove”事件处理程序。 .addEventListener() API 删除已添加的先前处理程序。过了一会儿,它们会有数百个,浏览器会调用每一个。

在计时器处理程序之外调用bClick()一次。此外,“mousemove”处理程序中的console.log()调用也无助于执行。