我在 map 上有一个区域被剪掉了!是否可以检测剪切区域外的点击,因此如果人们点击黑色暗淡区域,它会显示警报?
这是我的代码:
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';
我的 fiddle 代码在这里: http://jsfiddle.net/eGjak/2789/
问候安德烈亚斯
最佳答案
使用普通路径
当然可以,但是让我们稍微重构一下代码以便重用。如果您将剪切路径提取到单独的函数,以便我们可以将其重用于 HitTest :
function makePath() {
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(100,50);
ctx.lineTo(100, 100);
ctx.lineTo(200, 150);
ctx.lineTo(10, 150);
ctx.closePath();
}
然后我们可以用它来创建剪辑:
//...
ctx.save();
makePath(); // here
ctx.clip();
ctx.drawImage(image,0,0, canvas.width, canvas.height);
ctx.restore();
//...
以及 HitTest ,尽管我们会反转 bool 结果以在路径之外的点击时触发它。对于 HitTest ,我们可以使用 isPointInPath()它将使用当前路径并默认使用非零缠绕规则:
canvas.onclick = function(e) {
var rect = this.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top;
makePath(); // and here
if (!ctx.isPointInPath(x, y)) alert("Outside");
};
您还可以将路径存储在 Path2D 中对象而不是像这里一样在函数中,具体取决于您想要支持的新浏览器。
<强> Modified fiddle
使用 Path2D
我们可以使用前面提到的 Path2D 对象来代替该函数,该对象可以像这样重用。这些对象可以方便地存储多个路径数据,从而无需重建要测试的每个路径。缺点是目前并非所有浏览器都支持它们。
var p = new Path2D();
p.moveTo(10, 10);
p.lineTo(100,50);
p.lineTo(100, 100);
p.lineTo(200, 150);
p.lineTo(10, 150);
p.closePath();
然后用它来剪辑:
ctx.save();
ctx.clip(p); // hand over path object
ctx.drawImage(image,0,0, canvas.width, canvas.height);
ctx.restore();
和 HitTest :
if (!ctx.isPointInPath(p, x, y)) alert("Outside");
<强> Modified fiddle
关于javascript - Canvas - 检测剪切区域外的点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37564911/