我正在使用 drawImage
在 Canvas 上绘制图像。这是一个被透明像素包围的 PNG,如下所示:
如何为 Canvas 上该图像的可见部分添加纯色边框?澄清一下:我不想要一个围绕图像边界框的矩形。边界应环绕草地。
我确实考虑过使用阴影,但我真的不想要发光的边框,我想要实心的。
最佳答案
有点晚了,但只绘制图像偏移,这比分析边缘快得多:
var ctx = canvas.getContext('2d'),
img = new Image;
img.onload = draw;
img.src = "http://i.stack.imgur.com/UFBxY.png";
function draw() {
var dArr = [-1,-1, 0,-1, 1,-1, -1,0, 1,0, -1,1, 0,1, 1,1], // offset array
s = 2, // thickness scale
i = 0, // iterator
x = 5, // final position
y = 5;
// draw images at offsets from the array scaled by s
for(; i < dArr.length; i += 2)
ctx.drawImage(img, x + dArr[i]*s, y + dArr[i+1]*s);
// fill with color
ctx.globalCompositeOperation = "source-in";
ctx.fillStyle = "red";
ctx.fillRect(0,0,canvas.width, canvas.height);
// draw original image in normal mode
ctx.globalCompositeOperation = "source-over";
ctx.drawImage(img, x, y);
}
<canvas id=canvas width=500 height=500></canvas>
关于javascript - 在 Canvas 上围绕图像的非透明部分绘制边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28207232/