在画布上的图像的不透明部分周围绘制边框 [英] Draw border around nontransparent part of image on canvas
本文介绍了在画布上的图像的不透明部分周围绘制边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 drawImage
将图像绘制到画布上。这是一个由透明像素包围的PNG,如下所示:
如何在画布上的图像的可见部分添加纯色边框?澄清:我不想要一个矩形围绕图像的边界框。边界应该绕草地。
我考虑过使用阴影,但我真的不想要一个发光的边框,我想要一个坚实的边框。
解决方案
稍晚,但只是绘制图像 offset p>
< canvas id = canvas width = 500 height = 500>< / canvas>
I'm drawing an image onto a canvas using drawImage
. It's a PNG that is surrounded by transparent pixels, like this:
How can I add a solid-colored border to the visible part of that image on the canvas? To clarify: I don't want a rectangle that surrounds the image's bounding box. The border should go around the grass patch.
I did consider using shadows, but I don't really want a glowing border, I want a solid one.
解决方案
A bit late, but just draw the image offset which is much faster than analyzing the edges:
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>
这篇关于在画布上的图像的不透明部分周围绘制边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文