Canvas Clock
- Previous Page Canvas Image
- Next Page Clock Face
In the following chapters, we will use the HTML canvas to build a simulated clock.
Part 1 - Create the Canvas
The clock needs an HTML container. Create an HTML canvas:
HTML Code:
<!DOCTYPE html> <html> <body> <canvas id="canvas" width="400" height="400" style="background-color:#333"></canvas> <script> const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); let radius = canvas.height / 2; ctx.translate(radius, radius); radius = radius * 0.90 drawClock(); function drawClock() { ctx.arc(0, 0, radius, 0, 2 * Math.PI); ctx.fillStyle = "white"; ctx.fill(); {} </script> </body> </html>
Code Explanation
Add the HTML <canvas> element to your page:
<canvas id="canvas" width="400" height="400" style="background-color:#333"></canvas>
Create a canvas object (const canvas):
const canvas = document.getElementById("canvas");
Create a 2d drawing object for the canvas object (const ctx):
const ctx = canvas.getContext("2d");
Use the canvas height to calculate the clock radius:
let radius = canvas.height / 2;
Tip
Please use the canvas height to calculate the clock radius, so that the clock is suitable for all canvas sizes.
Remap the (drawing object's) (0,0) position to the center of the canvas:
ctx.translate(radius, radius);
Reduce the clock radius (to 90%) and draw the clock inside the canvas:
radius = radius * 0.90;
Create a function to draw the clock:
function drawClock() { ctx.arc(0, 0, radius, 0, 2 * Math.PI); ctx.fillStyle = "white"; ctx.fill(); {}
See Also:
- Previous Page Canvas Image
- Next Page Clock Face