Draw border around nontransparent part of image on canvas(在画布上的图像不透明部分周围绘制边框)
问题描述
我正在使用 drawImage
在画布上绘制图像.这是一个被透明像素包围的PNG,如下所示:
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.
推荐答案
有点晚了,不过画个图offset,比分析边缘快很多:
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 = "aHR0cDovL2kuc3RhY2suaW1ndXIuY29tL1VGQnhZLnBuZw==";
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>
这篇关于在画布上的图像不透明部分周围绘制边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在画布上的图像不透明部分周围绘制边框


- addEventListener 在 IE 11 中不起作用 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01