如何将 isPointInPath() 应用于多个路径
How to apply isPointInPath() to multiple path
我目前正在测试该点是否在多条路径内。例如,
const canvas = document.getElementsByTagName('canvas');
const ctx = canvas[0].getContext('2d');
ctx.beginPath();
ctx.moveTo(278, 110)
ctx.lineTo(390, 152)
ctx.lineTo(305, 255)
ctx.lineTo(221, 213)
ctx.closePath();
if (ctx.isPointInPath(284, 150)) {
console.log('Inside Path!')
};
但是,它工作错误,因为 ctx.isPointInPath(284, 150) 不工作并且 console.log('Inside Path!') 里面的 if 语句不 运行.但是点在线内。
我应该在哪里改进它?
您提供的代码没有任何问题。
为什么你的代码没有输出到控制台无法从提供的信息中推断出来。下面的示例是您的代码的副本(稍作修改)并按预期工作。
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.lineTo( 78, 10);
ctx.lineTo(190, 52);
ctx.lineTo(105, 149);
ctx.lineTo( 21, 113);
ctx.closePath();
ctx.stroke();
const p = {x: 84, y: 50};
ctx.isPointInPath(p.x, p.y) && console.log('Inside Path!');
ctx.fillRect(p.x-4, p.y, 9, 1);
ctx.fillRect(p.x, p.y-4, 1, 9);
<canvas id="canvas"></canvas>
我目前正在测试该点是否在多条路径内。例如,
const canvas = document.getElementsByTagName('canvas');
const ctx = canvas[0].getContext('2d');
ctx.beginPath();
ctx.moveTo(278, 110)
ctx.lineTo(390, 152)
ctx.lineTo(305, 255)
ctx.lineTo(221, 213)
ctx.closePath();
if (ctx.isPointInPath(284, 150)) {
console.log('Inside Path!')
};
但是,它工作错误,因为 ctx.isPointInPath(284, 150) 不工作并且 console.log('Inside Path!') 里面的 if 语句不 运行.但是点在线内。
我应该在哪里改进它?
您提供的代码没有任何问题。
为什么你的代码没有输出到控制台无法从提供的信息中推断出来。下面的示例是您的代码的副本(稍作修改)并按预期工作。
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.lineTo( 78, 10);
ctx.lineTo(190, 52);
ctx.lineTo(105, 149);
ctx.lineTo( 21, 113);
ctx.closePath();
ctx.stroke();
const p = {x: 84, y: 50};
ctx.isPointInPath(p.x, p.y) && console.log('Inside Path!');
ctx.fillRect(p.x-4, p.y, 9, 1);
ctx.fillRect(p.x, p.y-4, 1, 9);
<canvas id="canvas"></canvas>