我有一张带地图的帆布。我希望画布变暗,然后画布中的一个多边形是透明的(在焦点上,所以不要变暗)。
我无法让多边形的透明度发挥作用。现在我用颜色填充多边形,但是如何用透明的颜色填充多边形呢?
我做错了吗?
canv = document.getElementById("canvas");
ctx = canv.getContext("2d");
image = document.getElementById('img_holder');
ctx.drawImage(image,0,0, canv.width, canv.height);
ctx.fillStyle = "rgba(0, 0, 0, 0.5)";
ctx.fillRect(0, 0, 870, 500);
ctx.restore();
ctx.save();
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(100,50);
ctx.lineTo(100, 100);
ctx.lineTo(200, 150);
ctx.lineTo(10, 150);
ctx.fillStyle = "rgba(0, 0, 0, 0.5)";
ctx.closePath();
ctx.fill();
发布于 2016-02-24 04:38:46
要从透明的覆盖层中剪出一幅图像,您可以从以下两方面进行:
使用当前的设置,后者更容易使用clip
完成
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';
<canvas id="canvas" width="400" height="300"></canvas>
我还建议你为你的变量使用清晰的名字--缩短画布到canv几乎没有什么好处,但它使它更加清晰。此外,请确保使用var
关键字声明变量--这是常见的做法,与不声明变量略有不同,可能会出错。
https://stackoverflow.com/questions/35601342
复制相似问题