我有一个项目,我正在使用 nvd3.js 并想创建一个半圆形仪表。我如何创建它?
我确实尝试使用 guage.js,但我面临的问题是我无法为字符串类型的仪表添加自定义/标签标签,并且我找不到解决问题的方法。任何帮助表示赞赏。
这就是我想出的。它并不完美,工具提示相当无意义。此外,我一直在尝试提出渐变填充以使其具有 3D 外观,但还没有成功。
<div style="height: 200px; width: 350px;">
<div style="height: 350px; width: 350px;">
<svg id="gaugeContainer"></svg>
</div>
</div>
<script>
//d3.json("/api/gauge", updateChart);
updateChart({ "max": 100, "current": 90 });
function updateChart(data) {
var containerSvg = "gaugeContainer";
var height = 350;
var width = 350;
// The first graph section always starts at 0 degrees, but we
// want it to be horizontal so we rotate the whole thing -90
// degrees, then correct the labels.
// The formula for needle angle is ((current/max) * 180) - 90
// current / max will always be 1.0 or less,
// the fraction of max that the needle indicates,
// * 180 converts to degrees and -90 compensates for rotation.
var indicatorAngle = ((data.current / data.max) * 180) - 90;
var colors = ["green", "orange", "red", "white"];
// Apparently after 4 sections are defined, the fifth one is
// dead, as in not graphed. We play a little trick, defining a
// very small white section so we can display
// the max value at the end of its visible range.
// The key values could just as easily be strings.
var graphData = [
{ key: Math.round((data.max / 8) * 1), y: 1 },
{ key: Math.round((data.max / 8) * 3), y: 1 },
{ key: Math.round((data.max / 8) * 6), y: 2 },
{ key: Math.round((data.max / 8) * 8), y: 0.2 },
{ key: "", y: 3.8 }
];
var arcRadius = [
{ inner: 0.6, outer: 1 },
{ inner: 0.6, outer: 1 },
{ inner: 0.6, outer: 1 },
{ inner: 0.6, outer: 1 }
];
nv.addGraph(function () {
var chart = nv.models.pieChart()
.x(function (d) { return d.key })
.y(function (d) { return d.y })
.donut(true)
.showTooltipPercent(false)
.width(width)
.height(height)
.color(colors)
.arcsRadius(arcRadius)
.donutLabelsOutside(true)
.showLegend(false)
.growOnHover(false)
.labelSunbeamLayout(false);
d3.select("#" + containerSvg)
.datum(graphData)
.transition().duration(1)
.attr('width', width)
.attr('height', height)
.attr("transform", "rotate(-90)")
.call(chart);
// draw needle
d3.select("#" + containerSvg)
.append("path")
.attr("class", "line")
.attr("fill", "none")
.style("stroke", "gray")
.style("stroke-width", "1")
.attr("d", "M0, -3 L153, 0 0,3 Z")
.attr("transform", "translate(175,179) rotate(" + indicatorAngle + ")");
d3.select("#" + containerSvg)
.append("circle")
.attr("r", "6")
.attr("cx", "0")
.attr("cy", "0")
.style("stroke", "gray")
.style("stroke-width", "1")
.attr("transform", "translate(175,179) rotate(" + indicatorAngle + ")");
// correct text rotation
d3.select("#" + containerSvg).selectAll("text")
.attr("transform", "rotate(90)");
return chart;
});
}
</script>