캔버스의 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
}
이것은 모든 모양을 인식하므로 직사각형과 원 이외의 그림을 그릴 때 매우 유용합니다. 그러나,이 주요 단점은 모든 클릭 (또는 mouseover를 추가하는 경우 mousemove)에 다시 그리기해야한다는 것입니다. 내 경험에 비추어 볼 때 적어도 성능 문제가 발생하기 전에 적어도 300 개의 객체를 그리는 것이 좋습니다.
또한 어떤 이유로 든 고정되지 않은 상태로 유지되는 isPointInPath의 firefoxes 구현에 bug이 있다는 것에주의해야합니다. 그러나 행복하게 수정 충분히 쉽게
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_mozilla (X, Y)와 ctx.isPointInPath (X, Y)를 교체하고 나는 모바일 장치에 대한이 같은 짓을 한