Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
100
rated 0 times [  103] [ 3]  / answers: 1 / hits: 31328  / 13 Years ago, fri, september 9, 2011, 12:00:00

To play around with HTML5 canvas, I decided to make an app which draws an analogue clockface. Everything's fine, except that old lines don't get erased in the way that I would expect. I've included part of the code below - DrawHands() gets called once a second:



var hoursPoint = new Object();
var minutesPoint = new Object();
var secondsPoint = new Object();

function drawHands()
{
var now = new Date();

drawLine(centerX, centerY, secondsPoint.X, secondsPoint.Y, white, 1);
var seconds = now.getSeconds();
secondsPoint = getOtherEndOfLine(centerX, centerY, 2 * Math.PI / 60 * seconds, 0.75 * radius);
drawLine(centerX, centerY, secondsPoint.X, secondsPoint.Y, black, 1);

drawLine(centerX, centerY, minutesPoint.X, minutesPoint.Y, white, 3);
var minutes = now.getMinutes();
minutesPoint = getOtherEndOfLine(centerX, centerY, 2 * Math.PI / 60 * minutes, 0.75 * radius);
drawLine(centerX, centerY, minutesPoint.X, minutesPoint.Y, black, 3);

drawLine(centerX, centerY, hoursPoint.X, hoursPoint.Y, white, 3);
var hours = now.getHours();
if (hours >= 12) { hours -= 12; } // Hours are 0-11
hoursPoint = getOtherEndOfLine(centerX, centerY, (2 * Math.PI / 12 * hours) + (2 * Math.PI / 12 / 60 * minutes), 0.6 * radius);
drawLine(centerX, centerY, hoursPoint.X, hoursPoint.Y, black, 3);
}


To make sense of the above, there are two helper functions:




  • drawLine(x1, y1, x2, y2, color, thickness)

  • getOtherEndOfLine(x, y, angle, length)



The problem is that while all the hands get drawn as expected in black, they never get erased. I would expect that since the same line is drawn in white (the background colour) it would effectively erase what was previously drawn at that point. But this doesn't seem to be the case.



Anything I'm missing?


More From » html

 Answers
18

For reasons that I could expand upon, you should consider clearing your canvas and redrawing it entirely unless there are performance or compositing reasons not to.



You want clearRect, something like this:



//clear the canvas so we can draw a fresh clock
ctx.clearRect(0, 0, canvasWidth, canvasHeight);

//redraw your clock here
/* ... */

[#90177] Thursday, September 8, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
georgeh

Total Points: 193
Total Questions: 103
Total Answers: 111

Location: United States Minor Outlying Island
Member since Sat, May 28, 2022
2 Years ago
georgeh questions
Fri, Oct 8, 21, 00:00, 3 Years ago
Tue, Jan 5, 21, 00:00, 3 Years ago
Wed, Nov 25, 20, 00:00, 4 Years ago
Sat, Sep 12, 20, 00:00, 4 Years ago
Sat, Mar 7, 20, 00:00, 4 Years ago
;