Skip to content

Instantly share code, notes, and snippets.

@ajfarkas
Last active Oct 23, 2019
Embed
What would you like to do?
Bar Chart Clock

#Bar Chart Clock

For a simple bar chart that changes value (this example uses time), defining the width of the bar as a percentage of its container will suffice. 14 lines gets the job done.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
border: none;
}
path {
fill: none;
stroke-width: 9;
}
text {
font-family: helvetica, sans-serif;
font-size: 4px;
fill: #66acc8;
}
#hour { stroke: #342474; }
#minute { stroke: #426cc9; }
#second { stroke: #52dadb; }
</style>
</head>
<body>
<svg id="clock" width="960" height="480" viewBox="0 0 60 30">
<path id="hour" d="M0,5L60,5"/>
<path id="minute" d="M0,15L60,15"/>
<path id="second" d="M0,25L60,25"/>
<text class="hour" x="1" y="5">12 HOURS</text>
<text class="minute" x="1" y="15">60 MINUTES</text>
<text class="second" x="1" y="25">60 SECONDS</text>
</svg>
</body>
<script>
function getTime() {
var now = new Date()
var time = {
hour: now.getHours() % 12,
minute: now.getMinutes(),
second: now.getSeconds()
}
Object.keys(time).forEach(function(hand, i) {
var X = hand === 'hour' ? 5 : 1
d3.select('#'+hand).attr('d', 'M0,'+(10*i+5)+'L'+(X*time[hand])+','+(10*i+5) )
d3.select('.'+hand).text(time[hand]+' '+hand.toUpperCase()+'S')
})
}
var timer = window.setInterval(getTime, 1000)
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment