Principal Engineer | Mentor
Creating a clock with hands is a classic web development project that combines HTML, CSS, and JavaScript to display the current time in an analog format. In this article, we'll explore how to implement a clock with hands using TypeScript, providing examples for each step of the process.
The JSX structure
<Box
border={"7px solid black"}
borderRadius={"100%"}
width={"70vw"}
maxW={"400px"}
aspectRatio={1}
position={"relative"}
ref={clockRef}
display={"flex"}
alignItems={"center"}
justifyContent={"center"}
boxShadow={"0px 2px 9px #767575"}
>
<HourHandle
name="hour"
length={0.5}
thickness={10}
bg={"gray.500"}
/>
<HourHandle
name="minute"
length={0.7}
thickness={8}
bg={"gray.800"}
/>
<HourHandle
name="second"
length={0.8}
thickness={6}
bg={"red.800"}
/>
<Box
id="center"
w={5}
h={5}
bg="black"
borderRadius={"100%"}
position={"absolute"}
/>
{new Array(12).fill(0).map((item, index) => {
const degNumber = (2 - index) * 30;
const xNumber =
radius * 0.9 * Math.cos((degNumber * Math.PI) / 180);
const yNumber =
-(radius * 0.9) * Math.sin((degNumber * Math.PI) / 180);
const xLine = radius * Math.cos((degNumber * Math.PI) / 180);
const yLine = -radius * Math.sin((degNumber * Math.PI) / 180);
const degRotation = (index + 1) * 30;
return (
<>
<Box
className="xLine"
position={"absolute"}
key={`xLine-${index}`}
transform={`
translate(${xLine}px,${yLine}px)
rotate(${degRotation}deg)
`}
width={1}
height={2}
bg="black"
/>
<Box
className="xNumber"
position={"absolute"}
key={`clock-${index}`}
transform={`translate(${xNumber}px,${yNumber}px)`}
>
{index + 1}
</Box>
</>
);
})}
</Box>
</Box>
And then HoursHandle
const HourHandle = ({
name,
length,
bg,
thickness,
}: {
name: string;
length: number;
bg: string;
thickness: number;
}) => {
let deg = 0;
if (name === "second") {
deg = (second - 15) * 6;
} else if (name === "minute") {
deg = (minute - 15) * 6;
} else if (name === "hour") {
deg = (hour - 3) * 30 + (minute / 10) * 6;
}
return (
<Box
position={"absolute"}
width={radius * 2 * length}
transform={`rotate(${deg}deg)`}
transitionDuration={"300ms"}
height={"30px"}
display={"flex"}
alignItems={"center"}
>
<Box
id={`${name}-handle`}
width={"50%"}
aspectRatio={1}
height={`${thickness}px`}
bg={bg}
position={"absolute"}
right={0}
borderRadius={"30px"}
/>
</Box>
);
};
AND JS Code is pretty simple.
By combining HTML for structure, CSS for styling, and TypeScript for functionality, we've created a simple yet elegant analog clock with hands. This project serves as a great introduction to web development concepts and provides a foundation for further exploration and customization. Experiment with different styles and animations to make your clock uniquely yours!