I have been playing with HTML5 canvas elements creating some jQuery charting plug-ins, and one thing I was missing was to create "element like" objects (also in flash) that I could create, move around, assign events to atc.. So here is a little function that I wrote to compliment my drawRectangle function, now being able to draw "object-like" rectangles while singing events to them:
var createClickMap = function(canvas, x, y, w, h, f){
var m = function(x, y, w, h, mx, my){
var xEnd = (x+w);
yEnd = (y+h);
//x params
if(mx > x && mx < xEnd){
//y params
if(my > y && my < yEnd){
return true;
}
}
return false;
};
$(canvas).click(function(v){
var mX = v.pageX - this.offsetLeft,
mY = v.pageY - this.offsetTop;
if(m(x, y, w, h, mX, mY)){
f();
}
});
}
var drawRectangle = function(context, x, y, w, h, f) {
//draw shape
context.beginPath();
context.rect(x, y, w, h);
context.closePath();
context.fill();
//add event to a rectangle
if(typeof f == "function"){
createClickMap (canvas, x, y, w, h, f);
}
}
This mechanism could not be used for hovers for now, since this tracks the click of the canvas element, and the position within. I thinking about writing a little canvas toolkit that would somehow mimic the way we are used to coding in the DOM or flash, so I suppose, this function would be first building block...