HTML5 Canvas Example
HTML
<canvas id="canvas" width="480" height="320"></canvas>
<div id="hittest">Hit</div>
CSS
#hittest.red {
color: red;
}
JavaScript
$(document).ready(function() {
var $hittest = $("#hittest");
var canvas=document.getElementById("canvas");
var c = canvas.getContext("2d");
var logoImg = new Image();
/// create an off-screen canvas to hold image
var ocanvas = document.createElement('canvas');
var octx = ocanvas.getContext('2d');
var position = {
x: 50,
y: 50
}
logoImg.onload=function(){
/// set off-screen canvas to same size as image
ocanvas.width = this.width;
ocanvas.height = this.height;
octx.drawImage(this, 0, 0);
//c.clearRect (0, 0, canvas.width, canvas.height);
var grd = c.createLinearGradient(0, 0, canvas.width, canvas.height);
grd.addColorStop(0, "#9db7a0");
grd.addColorStop(1, "#e6e6e6");
c.fillStyle = grd;
c.fillRect (0, 0, canvas.width, canvas.height);
c.drawImage(logoImg, position.x, position.y, logoImg.width, logoImg.height);
}
logoImg.crossOrigin = '';
logoImg.src="http://dl.dropbox.com/u/139992952/car.png";
$(canvas).on('mousemove', function(e) {
/// correct mouse pos
var r = canvas.getBoundingClientRect(),
x = e.clientX - r.left,
y = e.clientY - r.top;
var hitted = x >= position.x && x <= position.x + logoImg.width && y >= position.y && y <= position.y + logoImg.height;
/// if we're in region we can test on off-screen canvas
if (hitted === true) {
var pixel = octx.getImageData(x - position.x, y - position.y, 1, 1).data;
hitted = pixel[3] > 0;
}
$hittest.toggleClass('red', hitted);
});
});