用户将鼠标悬停在画布上时创建动画

时间:2016-09-30 14:44:39

标签: javascript jquery canvas

我正在尝试添加图像并在用户悬停在画布上时为它们设置动画,并且一旦他们将鼠标移离画布我想要停止出现新图像。

为了达到这个目的,我试图在新图像上设置一个间隔,每100ms触发一次,然后如果用户将鼠标从画布上移开,该功能应该停止触发。

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

JS CODE BELOW

  //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>

1 个答案:

答案 0 :(得分:1)

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

var newImageInterval;

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