Skip to content

Instantly share code, notes, and snippets.

@natereed
Created September 5, 2023 23:07
Show Gist options
  • Save natereed/5bb9df5a053732d4fb1616ea782662b2 to your computer and use it in GitHub Desktop.
Save natereed/5bb9df5a053732d4fb1616ea782662b2 to your computer and use it in GitHub Desktop.
Analog Clock rendered using SVG in React
import React, { useState, useEffect } from 'react';
import './AnalogClock.css';
function AnalogClock() {
const [time, setTime] = useState(new Date());
useEffect(() => {
const intervalID = setInterval(() => {
setTime(new Date());
}, 1000);
// Cleanup the interval on component unmount
return () => clearInterval(intervalID);
}, []);
const seconds = time.getSeconds();
const minutes = time.getMinutes();
const hours = time.getHours() % 12;
// Calculate the rotation angles for clock hands
const secondHandAngle = (360 / 60) * seconds;
const minuteHandAngle = (360 / 60) * minutes + (360 / 60) * (seconds / 60);
const hourHandAngle = (360 / 12) * hours + (360 / 12) * (minutes / 60);
// Define the hand lengths
const secondHandLength = 70;
const minuteHandLength = 60;
const hourHandLength = 40;
return (
<div className="analog-clock">
<svg viewBox="0 0 200 200">
<circle cx="100" cy="100" r="90" fill="transparent" stroke="black" strokeWidth="3" />
{/* Draw the hour hand */}
<line
x1="100"
y1="100"
x2="100"
y2={100 - hourHandLength}
transform={`rotate(${90 - hourHandAngle} 100 100)`}
stroke="black"
strokeWidth="4"
/>
{/* Draw the minute hand */}
<line
x1="100"
y1="100"
x2="100"
y2={100 - minuteHandLength}
transform={`rotate(${90 - minuteHandAngle} 100 100)`}
stroke="black"
strokeWidth="3"
/>
{/* Draw the second hand */}
<line
x1="100"
y1="100"
x2="100"
y2={100 - secondHandLength}
transform={`rotate(${90 - secondHandAngle} 100 100)`}
stroke="red"
strokeWidth="2"
/>
{/* Draw the clock center */}
<circle cx="100" cy="100" r="3" fill="black" />
</svg>
</div>
);
}
export default AnalogClock;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment