phantom phantom - 2 months ago 22
jQuery Question

create animation while user is hovering over canvas

I am trying to add images and animate them when a user is hovering on the canvas, and once they move the mouse off the canvas I want to stop new images appearing.

To achieve this I have tried to set an interval on the new image to trigger every 100ms and then if the user moves the mouse off the canvas this function should stop triggering.

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>




Answer

I assume the problem is that the interval never clears. You need to assign the interval to a variable and then clear the interval by variable name:

var newImageInterval;

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