I have a canvas Element in my simple HTML page and it has few rectangles drawn using context.fillRect()
method. I need to interact with these drawn rectangles.
How can I do so? How can I bind onclick or onmouseover with these rectangles?
I have a canvas Element in my simple HTML page and it has few rectangles drawn using context.fillRect()
method. I need to interact with these drawn rectangles.
How can I do so? How can I bind onclick or onmouseover with these rectangles?
座標を追跡し、マウスが次のような長方形の1つにあるかどうかを確認する必要があります: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');
}
}
});
Canvasで選択可能な図形を作成および移動するためのチュートリアルをいくつか作成しました。これにより、必要なものを十分に理解できるようになります。
簡単に言うと、選択したいものすべてを追跡するだけです。