Analogue Clock
by IPWright83
HTML
<svg width="800" height="800">
<circle r="200" cx="200" cy="200"/>
<line id="hourHand" class="hand hour" x1="200" y1="200" x2="200" y2="0"></line>
<line id="minuteHand" class="hand minute" x1="200" y1="200" x2="200" y2="0"></line>
<line id="secondHand" class="hand second" x1="200" y1="200" x2="200" y2="0"></line>
</svg>
CSS
body {
background: #20262e;
}
circle {
fill: #fff;
}
.hand {
stroke: #20262e;
stroke-width: 2px;
}
.second {
stroke: red;
}
.hour {
stroke-width: 3px;
}
JavaScript
const radius = 200;
const hourRadius = radius - 100;
const minuteRadius = radius - 50;
const secondRadius = radius - 50;
const radiansInCircle = 2;
function getCoordinates(angle, radius) {
const x = radius * Math.sin(angle * Math.PI / 180);
const y = -radius * Math.cos(angle * Math.PI / 180);
return {
x,
y
};
}
const render = function(time) {
const secondsAngle = (360 / 60) * time.getSeconds();
const minutesAngle = (360 / 60) * time.getMinutes();
const hoursAngle = (360 / 12) * time.getHours();
const secondLocation = getCoordinates(secondsAngle, secondRadius);
const minuteLocation = getCoordinates(minutesAngle, minuteRadius);
const hourLocation = getCoordinates(hoursAngle, hourRadius);
d3.select("#hourHand")
.transition()
.duration(100)
.attr("x2", hourLocation.x + radius)
.attr("y2", hourLocation.y + radius);
d3.select("#minuteHand")
.transition()
.duration(100)
.attr("x2", minuteLocation.x + radius)
.attr("y2", minuteLocation.y + radius);
d3.select("#secondHand")
.transition()
.duration(100)
.attr("x2", secondLocation.x + radius)
.attr("y2", secondLocation.y + radius);
}
// Render every second
setInterval(() => {
let time = new Date();
render(time);
}, 1000);
// 1st Render
render(new Date());