Skip to content

Instantly share code, notes, and snippets.

@vasturiano
Last active April 20, 2017 19:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vasturiano/979b96ddd4f1461458bc3669528d0edc to your computer and use it in GitHub Desktop.
Save vasturiano/979b96ddd4f1461458bc3669528d0edc to your computer and use it in GitHub Desktop.
Gauge Meter
license: mit
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.23.1/babel.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/4.6.0/d3.min.js"></script>
<script src="//unpkg.com/d3-radial-axis@1.5/dist/d3-radial-axis.min.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<svg id="canvas"></svg>
<script type="text/babel" src="index.js"></script>
</body>
const EXTRA_ANGLE = 15,
whRatio = 2 / (Math.sin(deg2rad(EXTRA_ANGLE)) + 1.1),
r = Math.min(window.innerWidth, window.innerHeight * whRatio) / 2,
angleScale = d3.scaleLinear().domain([0, 100]).range([-90 - EXTRA_ANGLE, 90 + EXTRA_ANGLE])
// Size canvas
const svg = d3.select('#canvas')
.attr('width', r * 2)
.attr('height', r * 2 * whRatio)
.attr('viewBox', `${-r} ${-r} ${r*2} ${r*2*whRatio}`)
// Add axis
svg.append('g').classed('axis', true)
.call(d3.axisRadialInner(
angleScale.copy().range(angleScale.range().map(deg2rad)),
r - 5
))
// Add needle
const needle = svg.append('g')
.attr('transform', `scale(${r * 0.85})`)
.append('path').classed('needle', true)
.attr('d', ['M0 -1', 'L0.03 0', 'A 0.03 0.03 0 0 1 -0.03 0', 'Z'].join(' '))
.attr('transform', `rotate(${angleScale(0)})`)
// Add val label
const label = svg.append('text').classed('label', true)
.attr('x', 0)
.attr('y', r * 0.2)
.attr('text-anchor', 'middle')
.text('0')
// Move it around
setInterval(() => {
const newVal = Math.round(Math.random() * 100)
label.text(newVal)
needle.transition().duration(1500).ease(d3.easeElastic)
.attr('transform', `rotate(${angleScale(newVal)})`)
}, 1500)
function deg2rad(deg) { return deg * Math.PI / 180 }
body {
text-align: center;
font-family: Sans-serif;
margin: 0;
}
.axis .domain, .axis .tick line {
stroke-width: 2px;
stroke: DarkSlateGrey;
}
.axis .tick text {
font-size: 15px;
}
.needle {
fill: red;
}
.label {
fill: #AAA;
font-size: 18px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment