我遇到了更多挑战,因为我的画布元素可以重新缩放。所以首先当我绘制图形时,在我的例子中,我将它们与名称一起保存在一个数组中并绘制它们:
if (this.coInit == false)
{
let co = new TempCO ();
co.name= sensor.Name;
co.path = new Path2D();
co.path.arc(c.X, c.Y, this.radius, 0, 2 * Math.PI);
this.coWithPath.push(co);
}
let coWP = this.coWithPath.find(c=>c.name == sensor.Name);
this.ctx.fillStyle = color;
this.ctx.fill(coWP.path);
然后在鼠标事件中,我循环遍历项目并检查单击事件是否在路径中。但我还需要根据调整后的画布重新调整鼠标坐标:
getCursorPosition(event) {
const rect = this.ctx.canvas.getBoundingClientRect();
const x = ((event.clientX - rect.left ) / rect.width) * this.canvasWidth;
const y = ((event.clientY - rect.top) / rect.height) * this.canvasHeight;
this.coWithPath.forEach(c=>{
if (this.ctx.isPointInPath(c.path, x, y))
{
console.log("arc is hit", c);
//Switch light
}
});
}
所以我得到了画布的当前大小并将点重新缩放到原始大小。现在它起作用了!
这就是 TempCO 的样子:
export class TempCO
{
path : Path2D;
name : string;
}