JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://d3js.org/d3.v4.min.js"></script>
<body>
<div class="chart-gauge"></div>
<!-- <script type="text/javascript" src="d3_gauge.js"></script> -->
<script type="text/javascript">
// setInterval(function(){
// needle.moveTo(Math.random());
// }, 5000);
</script>
</body>
CSS
.chart-gauge
{
width: 400px;
margin: 100px auto
}
.chart-filled
{
fill: steelblue;
}
.chart-empty
{
fill: #dedede;
}
.needle, .needle-center
{
fill: #464A4F;
}
svg {
font: 10px sans-serif;
}
JavaScript
var needle;
(function(){
var barWidth, chart, chartInset, degToRad, repaintGauge,
height, margin, numSections, padRad, percToDeg, percToRad,
percent, radius, sectionIndx, svg, totalPercent, width;
percent = .65;
numSections = 1;
sectionPerc = 1 / numSections / 2;
padRad = 0.025;
chartInset = 10;
// Orientation of gauge:
totalPercent = .75;
el = d3.select('.chart-gauge');
margin = {
top: 20,
right: 20,
bottom: 30,
left: 20
};
// console.log(el[0][0].offsetWidth)
width = 400 - margin.left - margin.right;
height = width;
radius = Math.min(width, height) / 2;
barWidth = 40 * width / 300;
/*
Utility methods
*/
percToDeg = function(perc) {
return perc * 360;
};
percToRad = function(perc) {
return degToRad(percToDeg(perc));
};
degToRad = function(deg) {
return deg * Math.PI / 180;
};
// Create SVG element
svg = el.append('svg').attr('width', width + margin.left + margin.right).attr('height', height + margin.top + margin.bottom);
// Add layer for the panel
chart = svg.append('g').attr('transform', "translate(" + ((width + margin.left) / 2) + ", " + ((height + margin.top) / 2) + ")");
chart.append('path').attr('class', "arc chart-filled");
chart.append('path').attr('class', "arc chart-empty");
// svg.arc to arc
arc2 = d3.arc().outerRadius(radius - chartInset).innerRadius(radius - chartInset - barWidth)
arc1 = d3.arc().outerRadius(radius - chartInset).innerRadius(radius - chartInset - barWidth)
repaintGauge = function (perc)
{
var next_start = totalPercent;
arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc / 2);
next_start += perc / 2;
arc1.startAngle(arcStartRad).endAngle(arcEndRad);
arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad((1 - perc) / 2);
arc2.startAngle(arcStartRad + padRad).endAngle(arcEndRad);
chart.select(".chart-filled").attr('d', arc1);
...