Javascript 画布HTML5内路径上的悬停效果

Javascript 画布HTML5内路径上的悬停效果,javascript,html5-canvas,Javascript,Html5 Canvas,我在画布中有一条路径,我想在每个形状上添加悬停效果。当用户悬停在形状上时,我希望透明形状的背景色。现在,我已经将悬停函数附加到画布上,但我想将其附加到形状上 const canvas=document.getElementById('canvas'); const ctx=canvas.getContext('2d'); //ctx.fillStyle=“绿色”; //ctx.fillRect(0,0150150) //ctx.fillStyle='绿色'; //ctx.fillText(“h

我在画布中有一条路径,我想在每个形状上添加悬停效果。当用户悬停在形状上时,我希望透明形状的背景色。现在,我已经将悬停函数附加到画布上,但我想将其附加到形状上

const canvas=document.getElementById('canvas');
const ctx=canvas.getContext('2d');
//ctx.fillStyle=“绿色”;
//ctx.fillRect(0,0150150)
//ctx.fillStyle='绿色';
//ctx.fillText(“hello workd”,0,10)
ctx.beginPath();
ctx.moveTo(100100);
ctx.lineTo(350100)
ctx.lineTo(500,95)
ctx.lineTo(500130)
ctx.lineTo(350135)
ctx.lineTo(100130)
ctx.closePath()
ctx.fillStyle=“绿色”;
ctx.fill()
ctx.lineWidth=10
ctx.strokeStyle=“红色”
ctx.stroke()
ctx.beginPath();
ctx.moveTo(100200);
ctx.lineTo(350200)
ctx.lineTo(500195)
ctx.lineTo(500230)
ctx.lineTo(350235)
ctx.lineTo(100230)
ctx.closePath()
ctx.fillStyle=“绿色”;
ctx.fill()
ctx.lineWidth=10
ctx.strokeStyle=“红色”
ctx.stroke();
canvas.onmousemove=函数(e){
console.log('x',e.clientX)
console.log('y',e.clientY)
}

身体{
背景:红色;
显示器:flex;
证明内容:中心;
对齐项目:居中;
保证金:0;
}
#帆布{
背景:白色
}
路径2D上的点 可以使用和检查点是否在当前路径上。或者,为了方便起见,您可以使用对象来保存路径,并将其传递给函数,以节省每次鼠标移动时创建路径的需要

例子 下面的示例用于创建这两条路径。然后,
mousemove
事件使用检查鼠标是否位于路径上方。如果路径(1、2或无)发生更改,则清除画布并重新绘制反映新状态的路径

const ctx=canvas.getContext('2d'),鼠标={x:0,y:0,overPath:null};
常量样式={
默认值:{fillStyle:#0C0',strokeStyle:#F00',线宽:4},
上方:{fillStyle:#C008“,strokeStyle:#F0F8”,线宽:10},
};
常量路径=[
[100, 50, 350, 50, 500, 45, 500, 80, 350, 85, 100, 80],
[100, 150, 350, 150, 500, 145, 500, 180, 350, 185, 100, 180],
].map(创建路径);
canvas.addEventListener(“mousemove”,(e)=>{
mouse.x=e.offsetX;
mouse.y=e.offsetY;
选中鼠标悬停(路径);
canvas.style.cursor=mouse.overPath?“指针”:“默认”;
});
函数checkMouseOver(路径){
var-over;
对于(路径常数p){ctx.isPointInPath(p,mouse.x,mouse.y)&(over=p)}
如果(超过!==鼠标。超过){
mouse.overPath=over;
ctx.clearRect(0,0600200);
for(路径常数){
if(p==over){drawPath(p,styles.over)}
else{drawPath(p)}
}
}
}
函数createPath(路径){
变量i=0,p=newpath2d;
而(i
看一下: