如何解决有没有一种方法可以在旋转和平移点后检测其是否在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()
将其x
和y
坐标作为未变换,即在画布上作为绝对坐标,但是它确实将变换应用于给定的{ {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对象的转换后的副本
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。