There is a shape in my canvas, and I need to get all coordinates of its edge. The shape may be regular or irregular.
You can use the "Marching Squares" algorithm to detect the edge path of a closed shape:
This one by Michael Bostock for his excellent d3 visualization tool is great:
https://github.com/d3/d3-plugins/tree/master/geom/contour
The key to using his version of Marching Squares is defining the function that defines pixels inside your shape vs pixels outside your shape. Here's a function that uses the .getImageData pixel array (data
) to fetch non-transparent pixels:
// This is used by the marching ants algorithm
// to determine the outline of the non-transparent
// pixels on the image
var defineNonTransparent=function(x,y){
var a=data[(y*cw+x)*4+3];
return(a>20);
}
Example code and a Demo: http://jsfiddle.net/m1erickson/5v5hmo62/
Show Image
Show Outline Path