【发布时间】:2023-03-03 08:41:26
【问题描述】:
我需要在我的项目中绘制一个仪表。我正在使用 d3.js 来绘制仪表。 我Followed this link
效果很好,但我需要自定义针尖。我搜索了很多,但我不喜欢任何自定义指针指针的解决方案。
这是我的结果:
预期结果:
如何使用 d3.js 或 c3.js 实现它。如果有人有想法与我分享。 提前致谢。
【问题讨论】:
标签: javascript d3.js c3.js gauge
我需要在我的项目中绘制一个仪表。我正在使用 d3.js 来绘制仪表。 我Followed this link
效果很好,但我需要自定义针尖。我搜索了很多,但我不喜欢任何自定义指针指针的解决方案。
这是我的结果:
预期结果:
如何使用 d3.js 或 c3.js 实现它。如果有人有想法与我分享。 提前致谢。
【问题讨论】:
标签: javascript d3.js c3.js gauge
根据您提供的链接,您需要编辑:
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 上找到有关数学的更多详细信息。
我希望这会有所帮助。如需更详细的解释,请分享您自己的代码,以便我们进行具体审核。
更新:或者,这是一个基于问题创建者的 cmets 的更简单的解决方案:
只需在量规顶部添加一个具有适当半径的白色圆圈。把它放在针后面,并将其附加到图表中:
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
【讨论】: