Reputation: 43
I'm trying to create a JavaScript clock using canvas and I have everything on except that the previous lines don't disappear when I draw new ones I have checked the previous code on similar questions and its not working , this is what I have so far , I want to erase previously drawn lines in canvas , it keeps creating new lines one after the other. Thanks
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
var radius = canvas.height / 2;
ctx.translate(radius, radius)
radius = radius * 0.90
setInterval(drawClock, 1000);
function drawClock() {
drawFace(ctx, radius);
function drawFace(ctx, radius) {
ctx.beginPath();
ctx.arc(0, 0,8, 0, 2*Math.PI);
ctx.fillStyle = '#000000';
ctx.fill();
}
function drawFont(){
ctx.font = "30px Arial";
ctx.fillText("12",-17,-140);
ctx.font = "30px Arial ";
ctx.fillText("3",140,10);
ctx.font = "30px Arial";
ctx.fillText("6",-17,160);
ctx.font = "30px Arial";
ctx.fillText("9",-160,10);
drawFace();
}
function drawHands(length, width, color,ang){
ctx.save();
let deg= Math.PI/180;
ctx.rotate(ang);
ctx.moveTo(0,0);
ctx.strokeStyle = color;
ctx.lineWidth = width;
ctx.lineTo(0,length);
ctx.lineCap = 'round';
ctx.stroke();
ctx.restore();
drawFont();
}
function getTime(){
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
// console.log( hour+'::'+ minute + ': '+ second)
var hours = (hour*Math.PI/6)+
(minute*Math.PI/(6*60))+
(second*Math.PI/(360*60));
var minutes = minute=(minute*Math.PI/30)+(second*Math.PI/(30*60));
let seconds=(second*Math.PI/30);
// drawHands(-90, 5, 'blue', hours);
// drawHands(-120, 4, 'red', minutes);
drawHands(-150, 2, 'black', seconds);
console.log(seconds)
ctx.putImageData(imageData, 0, 0);
}
getTime();
}
my html
<canvas id="mycanvas" width="350px" height="350px"
style="border:8px inset gray; border-radius: 190px; margin: auto;">
</canvas>
Upvotes: 1
Views: 429
Reputation: 306
You need to erase the canvas each time you draw. It is best to think of HTML5 Canvas as drawing one frame at a time. Therefore, when you draw the next frame, you should clear out the previous frame using clearRect()
:
ctx.clearRect(-canvas.width/2, -canvas.height/2, canvas.width, canvas.height); // x, y, w, h
CodePen: https://codepen.io/chiss22/pen/wRKJON
Upvotes: 1
Reputation: 727
The easiest, and most common, solution is to clear the entire canvas and redraw the clock at each step.
setInterval(function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawClock();
}, 1000);
Other notes:
Upvotes: 0