[英]Javascript draw border around shape on Image canvas
I am searching for a solution to draw a border around all shapes on an Image.我正在寻找一种解决方案来围绕图像上的所有形状绘制边框。 I have already tried this solution Draw border around nontransparent part of image on canvas but this doesnt work for me.我已经尝试过这个解决方案在画布上的图像的非透明部分周围绘制边框,但这对我不起作用。
the solution I am looking for should look like this我正在寻找的解决方案应该是这样的
is there any libary/solution?有任何图书馆/解决方案吗?
Thank you谢谢
If you're drawing the all the shapes using ctx.fill()
, you can just call ctx.stroke()
before each call to ctx.fill()
.如果您使用ctx.fill()
绘制所有形状,则可以在每次调用ctx.stroke()
之前调用ctx.fill()
。 This will result in a line of width ctx.lineWidth/2
, since half of the line will be covered by the shape itself.这将导致一条宽度为ctx.lineWidth/2
的线,因为该线的一半将被形状本身覆盖。 However, his won't work for other methods such as ctx.drawImage()
or ctx.putImageData()
.但是,他不适用于其他方法,例如ctx.drawImage()
或ctx.putImageData()
。 Please specify how exactly you're drawing these shapes to the canvas to receive some more detailed help.请指定您在画布上绘制这些形状的准确程度,以获得更详细的帮助。
Edit: I think you can use the solution you already mentioned, you just need to make the non-black part of your image transparent.编辑:我认为您可以使用您已经提到的解决方案,您只需要使图像的非黑色部分透明即可。 You can do this by editing the the imageData of the canvas:您可以通过编辑画布的 imageData 来做到这一点:
var ctx = canvas.getContext("2d");
var imageData = ctx.getImageData(0,0,canvas.width,canvas.height);
for (let i=0;i<imageData.data.length;i+=4){
if (shouldBeTransparent(imageData.data[i],imageData.data[i+1],imageData.data[i+2]){
imageData.data[i+3] = 0;
}
}
ctx.putImageData(imageData,0,0);
function shouldBeTransparent(r,g,b){
return r!=0||g!=0||b!=0;
}
This will make all pixels that are not entirely black transparent, so you can continue with the method you already mentioned.这将使所有不完全黑色的像素透明,因此您可以继续使用您已经提到的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.