I spent around 10 minutes adding some extra mouse events to my particle simulation JavaScript this morning.

Sadly I used to w3schools to figure the available events but sometimes all you need is a quick reference.

Also this site is worth checking out.


Now for the code, I’ve only added two extra event listeners, mouseout and mouseover.

/* Initial function to start the animation */
function loadParticles() {
	// Mouse Event Listeners
        canvas.addEventListener("mousemove", mousePos, false);
	canvas.addEventListener ("mouseout", mouseOut, false);
	canvas.addEventListener ("mouseover", mouseIn, false);

	// Starts the canvas animation

The functions that are called when these mouse events are pretty basic. I made a global variable called isMouseOut that will hold a Boolean value.

/* Tracks when mouse leaves the canvas*/
function mouseOut(e) {
    if (!e) 
	e = event;
    isMouseOut = true;

/* Tracks when mouse enters the canvas*/
function mouseIn(e) {
    if (!e) 
	e = event;
    isMouseOut = false;

Now that I’m able to track when the mouse is over the canvas, I updated the updateParticles() function. If isMouseOut is set at true, then the particles will wiggle down as originally would. If the mouse is over the canvas the right side of the canvas, then the particles start falling towards the left. Likewise when the mouse is over the right side of the canvas the particles will start to fall towards the right.

function updateParticles() {
    for(var i in particles) {
        var part = particles[i];
        part.y += part.speed;
		// If mouse is outside the canvas
		if(isMouseOut == true){
			part.x += (-1+(Math.random()*2))
		// If mouse is inside the canvas
			// If mouse is on the right side of the canvas
			if(mouseX > (canvas.width / 2 ) ){
				part.x -= 1;
			// If mouse is on the left side of the canvas
			else if(mouseX < (canvas.width / 2 )){
				part.x += 1;
				part.x += (-1+(Math.random()*2))

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s