This project involves creating an analog clock for a school assignment using canvas. While I have managed to get the clock working, I am facing an issue with the clock hands leaving marks after each movement. Using the clearRect method seems to solve this problem but it also removes part of the background image (png). Is there a way to keep the image constant and only use clearRect to delete the hands?
window.onload = draw;
let myCanvas = document.getElementById("my-canvas");
var myCtx = myCanvas.getContext('2d');
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var canvas2 = document.createElement("canvas");
var ctx2 = canvas2.getContext("2d");
var radius = myCanvas.height / 2;
myCtx.translate(radius, radius);
radius = radius * 0.90
imageBack(myCtx);
setInterval(draw, 1000);
function imageBack(ctx2) {
var img = new Image();
img.addEventListener(
`load`,
function () {
ctx2.drawImage(img, -100, -100, 200, 200);
},
false
);
img.src = "watch1.png";
}
function draw() {
// set Time
setTime(myCtx, radius);
// myCtx.clearRect(-50, -50, 100, 100);
}
// set Time
function setTime(ctx, radius) {
// ctx.clearRect(-50,-50, 100,100);
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
hour = hour % 12;
hour = (hour * Math.PI) / 6 + (minute * Math.PI) / (6 * 60) + (second * Math.PI) / (360 * 60);
minute = (minute * Math.PI) / 30 + (second * Math.PI) / (30 * 60);
second = (second * Math.PI) / 30;
//set hours hand
drawHourHand(ctx, hour);
// set minutes hand
drawMinuteHand(ctx, minute);
// set seconds hand
drawSecondHand(ctx, second);
}
function drawHourHand(ctx, h) {
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.rotate(h);
ctx.lineTo(0, -radius * 0.3);
ctx.strokeStyle = "black";
ctx.closePath();
ctx.stroke();
ctx.rotate(-h);
}
// functions drawMinuteHand and drawSecondHand are almost identical to drawHourHand