I am getting a figure from an imageData that looks like this:
How could I get the edges of that figure? so that it looks more or less like this:
I have tried to validate for each pixel that the previous, next, top and bottom pixel is transparent in order to save that pixel and then draw on another canvas
var context = canvas.getContext("2d");
var pixelData = context.getImageData(0, 0, canvas.width, canvas.height);
var result = []
for (let index = 0; index < pixelData.data.length; index += 4) {
if (pixelData.data[index] != 0) {
if ((pixelData.data[index + canvas.width * 4]) == 0 || (pixelData.data[index - canvas.width * 4]) == 0 || pixelData.data[index - 4] == 0 || pixelData.data[index + 4] == 0) {
var x = index / 4 % canvas.width
var y = (index / 4 - x) / canvas.width;
result.push({ x: x, y: y })
}
}
}
context.clearRect(0, 0, canvas.width, canvas.height)
context.beginPath()
result.forEach(point => {
context.lineTo(point.x, point.y)
})
context.strokeStyle = "#000"
context.stroke()
But this does not seem to work very well.
How could I obtain the edge or, failing that, the polygon that is formed in that figure?



