function getEventPosition(ev){
var x, y;
if (ev.layerX || ev.layerX == 0) {
x = ev.layerX;
y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) { // Opera
x = ev.offsetX;
y = ev.offsetY;
}
return {x: x, y: y};
}
//注:使用上面这个函数,需要给Canvas元素的position设为absolute。
现在有了事件对象的坐标位置,下面就要判断Canvas里的图形,有哪些覆盖了这个坐标。
isPointInPath方法
Canvas的isPointInPath方法可以判断当前上下文的图形是否覆盖了某个坐标,比如:
cvs = document.getElementById('mycanvas');
ctx = canvas.getContext('2d');
ctx.rect(10, 10, 100, 100);
ctx.stroke();
ctx.isPointInPath(50, 50); //true
ctx.isPointInPath(5, 5); //false
接下来增加一个事件判断,就可以判断一个点击事件是否发生在矩形上:
cvs.addEventListener('click', function(e){
p = getEventPosition(e);
if(ctx.isPointInPath(p.x, p.y)){
//点击了矩形
}
}, false);
以上就是处理Canvas事件的基本方法,但是上面的代码还有局限,由于isPointInPath方法仅判断当前上下文环境中的路径,所以当Canvas里已经绘制了多个图形时,仅能以最后一个图形的上下文环境来判断事件,比如:
cvs = document.getElementById('mycanvas');
ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.rect(10, 10, 100, 100);
ctx.stroke();
ctx.isPointInPath(20, 20); //true
ctx.beginPath();
ctx.rect(110, 110, 100, 100);
ctx.stroke();
ctx.isPointInPath(150, 150); //true
ctx.isPointInPath(20, 20); //false
从上面这段代码可以看到,isPointInPath方法仅能识别当前上下文环境里的图形路径,而之前绘制的路径,无法回溯判断。这种问题的解决方法是:当点击事件发生时,重绘所有图形,每绘制一个就使用isPointInPath方法,判断事件坐标是否在该图形覆盖范围内。
循环重绘和事件冒泡
为了实现循环重绘,所以就要将图形的基本参数事先保存下来:
arr = [
{x:10, y:10, width:100, height:100},
{x:110, y:110, width:100, height:100}
];
cvs = document.getElementById('mycanvas');
ctx = canvas.getContext('2d');
draw();
function draw(){
ctx.clearRech(0, 0, cvs.width, cvs.height);
arr.forEach(function(v){
ctx.beginPath();
ctx.rect(v.x, v.y, v.width, v.height);
ctx.stroke();
});
}