HTML Mouse Tracking

I’ve was Googling on how work with mouse events and found these gems.

Safari HTML5 Canvas Guide

Adding Mouse and Touch Controls to Canvas

I really recommend reading the Safari guide and the following link has some good additional information too.

Mouse Events

quirksmode.org/js/events_mouse.html

While fiddling around with mouse events I’ve update my particle simulator code. You can find the original post here.

https://betamoore.wordpress.com/2012/04/22/simple-particle-animation-in-javascript/

Here is the code block of the start the script. The event listener in the init function listens for the mouse movement and calls mousePos function. Inside the mousePos(), the global variables mouseX and mouseY are updated with the current mouse coordinates.

// Globals
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

var particles = []; // Array for particle objects; particle = x, y, speed, radius, color
var mouseX; // Mouse X coordinate
var mouseY; // Mouse Y coordinate
var tick = 0; // Ticker variable

function init() {
    // Mouse Event Listeners
    canvas.addEventListener("mousemove", mousePos, false);

    // Starts the canvas animation
    animate();
}

 /* Tracks mouse position on canvas */
function mousePos(e) {
    if (!e) 
	e = event;
    mouseX = e.pageX - canvas.offsetLeft;
    mouseY = e.pageY - canvas.offsetTop;
}
 
 /* Animates the canvas */
function animate(){
    createParticles();
    updateParticles();
    resetParticles();
    drawParticles();
	
    setTimeout('animate()', 40);
}

Now that I’m able to track the position of the mouse. I’ve decided to try popping the particles when the mouse is hover over it. Accomplish this, I’ve updated my resetParticles function with this bit of logic. It’s still a little wonky on small particles though.

// If the mouse hovers over the particle
if( ( mouseX >= ( part.x - part.radius ) ) && 
    ( mouseX <= ( part.x + part.radius ) ) ) {
			
    if( ( mouseY >= ( part.y - part.radius ) ) &&
        ( mouseY <= ( part.y + part.radius ) ) ){
        part.color = randomColor();
        part.y = 0;
	part.x = Math.random()*canvas.width;
    }
}

I’m still working some other code but once that’s finished I’ll try setting up page hosted on github where you can see the code in action.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s