当用户将鼠标悬停在画布上时,我试图添加图像并对它们进行动画处理,一旦它们将鼠标从画布上移开,我想停止出现新图像。

为此,我尝试在新图像上设置一个间隔,以每100毫秒触发一次,然后,如果用户将鼠标从画布上移开,则此功能应停止触发。

canvas.addEventListener("mouseover", setInterval(newImage, 100), false);
canvas.addEventListener("mouseout", clearInterval(newImage), false);


下面的JS代码



  //gets canvas element
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  function newImage() {

    //random position on the canvas
    var randomPosition = parseInt(Math.random() * window.innerWidth);

    var images = [
      'http://www.convoy.me/image/landing/Scratcher.png',
      'http://www.convoy.me/image/landing/push_harder_0006.png'
    ];

    var y = window.innerHeight;

    //selects a random image
    var randomImage = parseInt(Math.random() * images.length);

    //IIFE draw
    (function draw() {
      var imageObj = new Image();
      imageObj.onload = function() {

        ctx.clearRect(randomPosition - imageObj.width, y, imageObj.width, imageObj.height);

        y -= 10;

        ctx.drawImage(imageObj, randomPosition - imageObj.width, y, imageObj.width, imageObj.height);

        if (y > -imageObj.height) {
          requestAnimationFrame(draw)
        }
      };
      imageObj.src = images[randomImage];
    })();
  }

  canvas.addEventListener("mouseover", setInterval(newImage, 100), false);
  canvas.addEventListener("mouseout", clearInterval(newImage), false);

<canvas id="canvas"></canvas>

最佳答案

我认为问题在于间隔永远不会清除。您需要将间隔分配给变量,然后按变量名称清除间隔:

var newImageInterval;

canvas.addEventListener("mouseover", function(){
  newImageInterval = setInterval(newImage, 100);
}, false);
canvas.addEventListener("mouseout", function(){
  clearInterval(newImageInterval);
}, false);

关于javascript - 当用户将鼠标悬停在 Canvas 上时创建动画,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39794186/

10-16 21:00