-1

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.

Imagine this png enter image description here

the solution I am looking for should look like this enter image description here

is there any libary/solution?

Thank you

Patsch
  • 71
  • 1
  • 2
  • 11
  • How exactly the question you posted doesn't work? Does it draw? Does it skip some objects? – deathangel908 Feb 07 '19 at 15:19
  • The solution I mentioned does only work for small images (300x300). If I load Images with higher resolution the app will freeze. If I load the first Image in the example with a small resolution the app will only draw a border around the image itself not around the obstacles. – Patsch Feb 08 '19 at 08:12

1 Answers1

2

If you're drawing the all the shapes using ctx.fill(), you can just call ctx.stroke() before each call to 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. However, his won't work for other methods such as ctx.drawImage() or 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:

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.

peabrainiac
  • 998
  • 9
  • 16
  • I am not drawing these shapes. It is a png which gets loaded into a canvas. I need to detect the black shapes, because I want to implement a collision warning. – Patsch Feb 07 '19 at 15:35
  • So what exactly are you trying to achieve? Collision detection could simply be achieved by testing the color of a specific pixel, without doing any extra drawing at all. Or do you want the lines as a visual indicator? – peabrainiac Feb 07 '19 at 15:42
  • Yes I know, but the first step would be to detect the black shapes and draw - like in the example above - a red border around them. The red border should represent the minimum distance to an obstacle. – Patsch Feb 07 '19 at 15:51
  • I just updated my answer; let me know if that approach works for you. – peabrainiac Feb 07 '19 at 16:21