我需要在我的项目中绘制一个仪表。我正在使用 d3.js 绘制仪表。 我 Followed this link
效果很好,但我需要自定义针尖。我搜索了很多,但我不喜欢任何自定义指针的解决方案。
这是我的结果:
预期结果:
如何使用 d3.js 或 c3.js 实现它。如果有人有想法与我分享。 提前致谢。
最佳答案
根据您提供的链接,您需要编辑:
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));
};
在此代码中,附加圆是针的中心,路径是针尖。 d个位置是使用recalcPointerPos函数计算的
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;
};
如您所见,此函数的返回部分发送针尖路径的坐标。编辑此返回值将允许您对其进行自定义。
更新:可以在这个 page by Jake Trent 上找到更多涉及的数学细节。 .
希望对您有所帮助。更详细的解释,请分享您自己的代码,以便我们具体审查。
更新:或者,这里有一个基于问题创建者评论的更简单的解决方案:
只需在仪表顶部附加一个具有适当半径的白色圆圈。将其放在针后并将其附加到图表中:
chart.append("circle")
.attr("r", 70)
.style("fill", "white")
;
看看这个 plunker:https://plnkr.co/edit/25KSME35LewdkQaybBc5?p=preview
更新 2:想出了一个更好但稍微复杂一点的方法来做与上面相同的事情,但使用 SVG Masks . 在这种方法中,您可以避免创建白色圆圈,因此如果您将仪表放在不同的背景上,它就不会显示白色圆圈。此方法使用掩码。我们必须定义一个带有两个圆圈的掩码:
- 填充为白色的圆圈 - 这是将要显示的区域,即半径将是整个仪表的半径。
- 一个黑色填充的圆圈 - 这是将被隐藏/遮盖的区域。
此掩码应在附加弧路径后定义为:
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 以获得此方法的演示。 https://plnkr.co/edit/4SQSNO?p=preview
关于javascript - 如何使用 D3.js 或 C3.js 自定义 Gauge 指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50644710/