Html5 canvas 如何将onclick事件绑定到piechart段?

Html5 canvas 如何将onclick事件绑定到piechart段?,html5-canvas,Html5 Canvas,如何将onclick事件绑定到piechart段 饼图部分实际上是一个楔子。你有几种方法来测试楔子 一种方法是数学方法: 测试鼠标是否在楔块创建的圆的半径范围内 如果半径测试为真,则计算鼠标相对于圆中心点的角度 将该角度与每个楔块进行比较。如果角度介于特定楔体圆弧的起始角度和结束角度之间,则鼠标位于该楔体内部 另一种方法是使用canvas的内置路径命中测试方法:isPointInPath 重新定义一个楔子。实际上没有必要去敲打或填补这个楔子。只需执行从beginPath到closePath

如何将onclick事件绑定到piechart段


饼图部分实际上是一个楔子。你有几种方法来测试楔子

一种方法是数学方法:

  • 测试鼠标是否在楔块创建的圆的半径范围内

  • 如果半径测试为真,则计算鼠标相对于圆中心点的角度

  • 将该角度与每个楔块进行比较。如果角度介于特定楔体圆弧的起始角度和结束角度之间,则鼠标位于该楔体内部

另一种方法是使用canvas的内置路径命中测试方法:
isPointInPath

  • 重新定义一个楔子。实际上没有必要去敲打或填补这个楔子。只需执行从
    beginPath
    closePath
    的命令即可

  • 使用
    context.isPointInPath(mouseX,mouseY)
    点击测试鼠标是否在楔块内

  • 如果isPointInPath返回true,则表示您在鼠标下发现了楔块。如果没有,则重新定义并点击测试每个其他楔子

这是我不久前编写的一个代码,它在悬停时测试饼图的楔形,在单击楔形时将楔形移出饼图

它使用
isPointInPath
方法进行命中测试:

var canvas=document.getElementById(“canvas”);
var ctx=canvas.getContext(“2d”);
ctx.lineJoin=“圆形”;
var$canvas=$(“#canvas”);
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var scrollX=$canvas.scrollLeft();
var scrollY=$canvas.scrollTop();
功能楔块(cx、cy、半径、星形度、端角度、填充、笔划、线宽){
这个.cx=cx;
this.cy=cy;
这个半径=半径;
this.startAngle=startAngleDeg*Math.PI/180;
this.endAngle=endAngleDeg*Math.PI/180;
this.fill=填充;
这个笔划=笔划;
this.lineWidth=线宽;
这个偏移量=0;
this.offsetY=0;
这是1.rr=半径*半径;
this.centerX=cx;
this.centerY=cy;
this.midAngle=this.startAngle+(this.endAngle-this.startAngle)/2;
此偏移距离=15;
this.explodeX=this.offsetDistance*Math.cos(this.midAngle);
this.explodeY=this.offsetDistance*Math.sin(this.midAngle);
this.isexploed=false;
};
Wedge.prototype.draw=功能(填充、冲程){
定义();
这个。填充笔划(填充,笔划);
ctx.beginPath();
ctx.arc(this.cx,this.cy,this.radius,0,Math.PI*2);
ctx.closePath();
ctx.lineWidth=0.50;
ctx.stroke();
}
Wedge.prototype.fillStroke=函数(填充,笔划){
ctx.fillStyle=fill | | this.fill;
ctx.fill();
ctx.strokeStyle=冲程,this.stroke;
ctx.lineWidth=此.lineWidth;
ctx.stroke();
}
Wedge.prototype.define=函数(){
var x=this.cx+this.offsetX;
变量y=this.cy+this.offsetY;
ctx.beginPath();
弧(x,y,this.radius,this.startAngle,this.endAngle);
ctx.lineTo(x,y);
ctx.closePath();
}
Wedge.prototype.ptantangle=函数(弧度角){
var xx=(this.cx+this.offsetX)+this.radius*Math.cos(弧度角);
var yy=(this.cy+this.offsetY)+this.radius*Math.sin(radianAngle);
返回({
x:x,
y:y
});
}
Wedge.prototype.explode=函数(ISExploed){
this.isexploed=isexploed;
this.offsetX=isexploed?this.explodeX:0;
this.offsetY=isexploed?this.explody:0;
这个.draw();
}
Wedge.prototype.isPointInside=函数(x,y){
var dx=x-(this.cx+this.offsetX);
var dy=y-(this.cy+this.offsetY);
如果(dx*dx+dy*dy>this.rr){
返回(假);
}
变量角度=(数学atan2(dy,dx)+数学PI*2)%(数学PI*2);

return(angle>=this.startAngle&&angle不清楚您在问什么。请详细说明您试图实现的目标,在问题中包含相关代码-如果可能,设置小提琴(或使用内置的实时代码生成器)以显示您需要修复的部分。