【发布时间】:2016-06-01 18:10:36
【问题描述】:
我在地图上有一个区域被剪掉了!是否可以在剪切区域外点击检测,所以如果人们点击黑色变暗区域,它会显示警报?
这是我的代码:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var image = new Image;
image.addEventListener('load', function(){
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(0, 0, 0, 0.5)";
ctx.fillRect(0, 0, 870, 500);
// Use save and restore to make sure the canvas restores its non-clipping path setup after clipping
ctx.save();
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(100,50);
ctx.lineTo(100, 100);
ctx.lineTo(200, 150);
ctx.lineTo(10, 150);
ctx.closePath();
// Use the path just created as a clipping path
ctx.clip();
// Draw anywhere in the image, only inside the clipping path will be drawn
ctx.drawImage(image,0,0, canvas.width, canvas.height);
// restore so you can draw outside the clipping path again
ctx.restore();
});
image.src = 'http://www.marinadivenezia.it/media/467/w-876/h-506/00-MAPPA-2015-GENERICA.jpeg';
我的小提琴代码在这里: http://jsfiddle.net/eGjak/2789/
问候安德烈亚斯
【问题讨论】:
-
是的,您可以检测点击事件的 X-Y 坐标,通过该详细信息您可以知道点击是在路径内还是在路径外。
-
如果剪辑区域是一个多边形,你可以看看这个How can I determine whether a 2D Point is within a Polygon?
-
@jcubic 这是通过方法 isPointInPath()(和 isPointInStroke())内置的,包括奇偶和非零绕组测试。
标签: javascript jquery canvas html5-canvas