canvas の isPointInPath メソッドを使用して、マウス イベント処理を追加できます。以下のようなもの(未テスト)。
// add click event handler to canvas
// on click
var rect = canvas.getBoundingClientRect();
var mouseX = e.clientX - rect.left;
var mouseY = e.clientY - rect.top;
ctx.beginPath()
// draw stuff
if (ctx.isPointInPath(mouseX, mouseY)) {
// handle click
}
これはあらゆる形状を認識します。これは、長方形と円以外のものを描く場合に非常に便利です。ただし、これの主な欠点は、クリックするたびに再描画する必要があることです (または、マウスオーバーを追加する場合は mousemove)。私の経験では、パフォーマンスの問題が発生する前に、少なくとも 300 個のオブジェクトを描画できます。
また、何らかの理由で修正されていない isPointInPath の firefox 実装にバグがあることにも注意してください。しかし幸いなことに、修正は簡単です
CanvasRenderingContext2D.prototype.isPointInPath_mozilla = function( x, y )
{
if (navigator.userAgent.indexOf('Firefox') != -1){
this.save();
this.setTransform( 1, 0, 0, 1, 0, 0 );
var ret = this.isPointInPath( x, y );
this.restore();
} else
var ret = this.isPointInPath( x, y );
return ret;
}
ctx.isPointInPath(x,y) を ctx.isPointInPath_mozilla(x,y) に置き換えるだけで、すべてが機能します