如何将isPointInPath()应用于多个路径



我目前正在测试该点是否在多个路径内。例如,

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(284150(不起作用,如果句子不运行,则在里面控制台.log('Inside Path!'(。但重点在底线之内。

我应该在哪里改进?

您提供的代码没有任何问题。

为什么你的代码没有输出到控制台无法从提供的信息中推断出来。下面的示例是您的代码的副本(稍作修改(,可以按预期工作。

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>

最新更新