Created
September 5, 2023 23:07
-
-
Save natereed/5bb9df5a053732d4fb1616ea782662b2 to your computer and use it in GitHub Desktop.
Analog Clock rendered using SVG in React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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