How to find the associated polygon from pixel canvas HTML5 -


i working on html5 canvas application. able find co ordinates , hex value of point clicking on canvas. if suppose clicking area have filled polygon (and know color of polygon). there way or algorithm return enclosing co-ordinates drew polygon ??

solution

store polygon points in objects or array , use canvas method:

var boolean = context.ispointinpath(x, y); 

by storing points objects/arrays can iterate through collection re-build path each polygon , call method above (no need redraw polygon checks).

if have hit know object current. can store other meta data on these objects such color.

example

you can make simple class store coordinates color (a basic objectyou can extend needed):

function polygon(pts, color) {     this.points = pts;     this.color = color;     return this; } 

then define points:

/// object collection var mypolygons = [];  /// add polygons mypolygons.push( new polygon([[10,10], [30,30], [70,70]], 'black') ); mypolygons.push( new polygon([[50,40], [70,80], [30,30]], 'red') ); 

render polygons

then render polygons:

for(var = 0, p, points; p = mypolygons[i]; i++) {       points = p.points;       ctx.beginpath();      ctx.moveto(points[0][0], points[0][1]);       for(var t = 1; t < points.length; t++) {          ctx.lineto(points[t][0], points[t][1]);      }      ctx.closepath();       ctx.fillstyle = p.color;      ctx.fill(); } 

check if point in path

then check hit based on position x, y when click.

as can see function identical render function (and of course can refactor them single function) doesn't draw anything, re-builds path check.

for(var = 0, p, points; p = mypolygons[i]; i++) {       points = p.points;       ctx.beginpath();      ctx.moveto(points[0][0], points[0][1]);       for(var t = 1; t < points.length; t++) {          ctx.lineto(points[t][0], points[t][1]);      }      ctx.closepath();       /// instead of drawing anything, check:      if (ctx.ispointinpath(x, y) === true) {          alert('hit: ' + p.color);          return;      } } 

conclusion

typically turn out faster iterating bitmap array (which solution). because checks done internally in compiled code.

in future have access building path objects ourselves , can pass single path object holding path info instead of re-building it, means higher speed.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -