I am trying to find a point in a Path2D object in an HTML5 canvas using JavaScript.
var path = new Path2D;
path.rect(0,0,100,100);
// declare the path
ctx.beginPath();
ctx.save()
ctx.translate(500,500);
ctx.rotate(Math.PI/2);
ctx.fill(path);
ctx.restore()
// draw the path after translation and rotation
ctx.isPointInPath(path,505,500) // return false because path is defined at 0, 0 not 500,500 where path is drawn
// Is there a way know if the points are in the path where it is drawn.
// I do not want to re - define the path, but if there is a way to move it that would work.
Please understand that this code is simplified, and the path I am using is not a generic shape, so this needs to work for any given 2d path. This is not a question about syntax so please excuse the undefined variables.
isPointInPath()takes itsxandycoordinates as untransformed, i.e as absolute coordinates on the canvas, however it does apply the transformations on the givenpath.So you need to call it with the applied transformation (i.e, get rid of this
ctx.restore()).However your numbers don't add up:
But if you use correct coordinates, it will work as expected:
And if one day you really need to transform a Path2D object, you can refer to this post which uses the second parameter
matrixofPath2D.add(path, matrix)to return a transformed copy of the Path2D object.