use*_*575 8 javascript html5-canvas
我的简单HTML页面中有一个canvas元素,它使用context.fillRect() 方法绘制的矩形很少.我需要与这些绘制的矩形进行交互.
我怎么能这样做?如何用这些矩形绑定onclick或onmouseover?
pim*_*vdb 12
你需要跟踪坐标并检查鼠标是否在这样的矩形之一:http://jsfiddle.net/eGjak/13/.
显然,而不是click你也可以使用mouseover.
var ctx = $('#cv').get(0).getContext('2d');
var rects = [[0, 0, 100, 100], [0, 150, 50, 100]]; // [x, y, width, height]
for(var i=0;i<rects.length;i++) {
ctx.fillRect(rects[i][0], // fill at (x, y) with (width, height)
rects[i][1],
rects[i][2],
rects[i][3]);
}
$('#cv').click(function(e) {
var x = e.offsetX,
y = e.offsetY;
for(var i=0;i<rects.length;i++) { // check whether:
if(x > rects[i][0] // mouse x between x and x + width
&& x < rects[i][0] + rects[i][2]
&& y > rects[i][1] // mouse y between y and y + height
&& y < rects[i][1] + rects[i][3]) {
alert('Rectangle ' + i + ' clicked');
}
}
});
Run Code Online (Sandbox Code Playgroud)