Javascript 如何使用D3.js或C3.js定制仪表指针?
我需要在我的项目中绘制一个标尺。我正在使用d3.js绘制一个标尺。 我 它工作得很好,但我需要定制针尖。我搜索了很多,但我不喜欢任何定制指针的解决方案 这是我的结果: 预期结果: 如何使用d3.js或c3.js实现它。如果有人有想法,请与我分享。Javascript 如何使用D3.js或C3.js定制仪表指针?,javascript,d3.js,c3.js,gauge,Javascript,D3.js,C3.js,Gauge,我需要在我的项目中绘制一个标尺。我正在使用d3.js绘制一个标尺。 我 它工作得很好,但我需要定制针尖。我搜索了很多,但我不喜欢任何定制指针的解决方案 这是我的结果: 预期结果: 如何使用d3.js或c3.js实现它。如果有人有想法,请与我分享。 提前感谢。根据您提供的链接,您需要编辑: Needle.prototype.render = function() { this.el.append('circle').attr('class', 'needle-center').attr('
提前感谢。根据您提供的链接,您需要编辑:
Needle.prototype.render = function() {
this.el.append('circle').attr('class', 'needle-center').attr('cx', 0).attr('cy', 0).attr('r', this.radius);
return this.el.append('path').attr('class', 'needle').attr('id', 'client-needle').attr('d', recalcPointerPos.call(this, 0));
};
在此代码中,附加圆是针的中心,路径是针尖。使用recalcPointerPos函数计算d位置
var recalcPointerPos = function(perc) {
var centerX, centerY, leftX, leftY, rightX, rightY, thetaRad, topX, topY;
thetaRad = percToRad(perc / 2);
centerX = 0;
centerY = 0;
topX = centerX - this.len * Math.cos(thetaRad);
topY = centerY - this.len * Math.sin(thetaRad);
leftX = centerX - this.radius * Math.cos(thetaRad - Math.PI / 2);
leftY = centerY - this.radius * Math.sin(thetaRad - Math.PI / 2);
rightX = centerX - this.radius * Math.cos(thetaRad + Math.PI / 2);
rightY = centerY - this.radius * Math.sin(thetaRad + Math.PI / 2);
return "M " + leftX + " " + leftY + " L " + topX + " " + topY + " L " + rightX + " " + rightY;
};
如您所见,此函数的返回部分发送针尖路径的坐标。编辑此返回值将允许您对其进行自定义
更新:更多关于这方面的数学细节可以在这里找到
我希望这有帮助。如需更详细的解释,请分享您自己的代码,以便我们可以具体查看
更新:或者,根据问题创建者的评论,这里有一个更简单的解决方案:
只需在量规顶部附加一个具有适当半径的白色圆圈。将其放在指针后面,并将其附加到图表中:
chart.append("circle")
.attr("r", 70)
.style("fill", "white")
;
请查看此plunker:
更新2:想出了一种更好但稍微复杂的方法来实现上述功能,但使用。
在这种方法中,您可以避免创建白色圆圈,因此,如果将仪表放置在不同的背景上,它将不会显示白色圆圈。此方法使用遮罩。我们必须用两个圆定义遮罩:
chart.append("defs")
.append("mask")
.attr ("id", "mask-1")
.append("circle")
.attr("r", 180)
.style("fill", "#FFF")
;
d3.select("#mask-1")
.append("circle")
.attr("r", 70)
.style("fill", "#000");
接下来,我们需要将此遮罩添加到针和针中心,如下所示:
Needle.prototype.render = function() {
this.el.append('circle').attr('class', 'needle-center').attr('cx', 0).attr('cy', 0).attr('r', this.radius)
.attr("mask", "url(#mask-1)");
return this.el.append('path').attr('class', 'needle').attr('id', 'client-needle').attr('d', recalcPointerPos.call(this, 0))
.attr("mask", "url(#mask-1)");
};
请查看此plunker以获得此方法的演示。
嗨@Coola,谢谢你的回复。()这就是我找到例子的地方。……嗨,帕提班,我已经更新了答案。我在一个页面上添加了一个链接,该页面讨论了仪表的数学原理,因此您可以根据自己的喜好对其进行定制。或者,我添加了一个更简单的解决方案。让我知道这是否足够好。不客气,帕提班。我还添加了另一个解决方案,在其他情况下可能更有用。此方法使用遮罩遮住量规的中心,而不是使用圆,从而创建一个不可见的切口。