有没有一种方法可以在旋转和平移点后检测其是否在Path2D对象中?

问题描述

我正在尝试使用JavaScript在HTML5画布的Path2D对象中找到一个点。

var path = new Path2D;
path.rect(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.

请理解,此代码已简化,并且我使用的路径不是通用形状,因此这需要适用于任何给定的2d路径。这不是语法问题,请原谅未定义的变量。

解决方法

isPointInPath()将其xy坐标作为未变换,即在画布上作为绝对坐标,但是它确实将变换应用于给定的{ {1}}。

因此,您需要使用已应用的转换来调用它(即摆脱此path)。

但是您的电话号码未加:

ctx.restore()
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d');
const path = new Path2D;
path.rect(0,100,100);
// declare the path

ctx.translate(500,500);
ctx.rotate(Math.PI / 2)
ctx.fillStyle = "green";
ctx.fill(path);

// using fixed values
const x = 505;
const y = 500;
console.log(ctx.isPointInPath(path,x,y));

// reset to identity matrix
ctx.setTransform(1,1,0);
ctx.fillStyle = "red";
ctx.fillRect(x-2,y-2,4,4);

document.scrollingElement.scrollBy(600,650);

但是,如果您使用正确的坐标,它将按预期工作:

<canvas id="canvas" width="600" height="650"></canvas>
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d');
const path = new Path2D;
path.rect(0,500);
ctx.rotate(Math.PI / 2)
ctx.fillStyle = "green";
ctx.fill(path);

// using fixed values
const x = 495;
const y = 505;
console.log(ctx.isPointInPath(path,650);

如果有一天您确实需要转换Path2D对象,则可以参考this post,它使用<canvas id="canvas" width="600" height="650"></canvas>的第二个参数matrix返回Path2D对象的转换后的副本