Canvas Hit Test
by Amit Vishwakarma
HTML
<canvas id="canvas"></canvas>
CSS
html, body {
margin: 0;
padding: 0;
}
body {
background: #eee;
}
canvas {
background: #fff;
display: block;
margin: 40px auto;
}
JavaScript
// Set Initival Variables
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
shapes = [],
shapeCount = 20,
normalColor = '#666',
hoverColor = '#3f3',
strokeColor = '#222',
strokeWidth = 2,
mouseX = 0,
mouseY = 0,
randomRange = function(minRange,maxRange){
return Math.floor(Math.random() * (maxRange - minRange + 1)) + minRange;
};
// Set Canvas Dimensions
canvas.width = 500;
canvas.height = 500;
// Set Canvas Context Styles
context.lineWidth = strokeWidth;
context.strokeStyle = strokeColor;
// Create Shapes
while(shapeCount--){
// each shape is an object with its own properties
shapes.push({
x: randomRange(0, canvas.width),
y: randomRange(0, canvas.width),
width: randomRange(20, 150),
height: randomRange(20, 150),
hovering: false
});
};
// Update Shapes
var updateShapes = function(){
var i = shapes.length;
// loop over all shapes
while(i--){
var shape = shapes[i];
// check for hover by comparing the mouseX and mouseY to the current shape's x, y, width, and height properties
if(mouseX >= shape.x && mouseX <= shape.x + shape.width && mouseY >= shape.y && mouseY <= shape.y + shape.height){
shape.hovering = true;
} else {
shape.hovering = false;
}
};
};
// Render Shapes
var renderShapes = function(){
var i = shapes.length;
// loop over all shapes
while(i--){
var shape = shapes[i];
context.beginPath();
context.rect(shape.x, shape.y, shape.width, shape.height);
context.closePath();
// change the color if the shape is currently being hovered over
if(shape.hovering){
context.fillStyle = hoverColor;
} else {
context.fillStyle = normalColor;
}
context.fill();
context.stroke();
};
};
// Update Mouse Position on...