the_camino the_camino - 3 months ago 6
Javascript Question

Line not clearing from HTML5 Canvas

I'm trying to solve an odd artifact that is occurring in my HTML5 Canvas animation. I'm trying to surround the text with lines that follow each other. When I get to clearing the third line, there is a line still there as if

clearRect()
didn't work correctly.

I've already googled and my draw functions do indeed use
beginPath()
and
closePath()
respectively, so you can imagine my frustration when this thing doesn't clear.

I'm hoping someone can help me see where I've gone wrong with this animation.

Here's an example of the draw code (because stack overflow is forcing me to put code in here if I link to JSFiddle)

function drawArc(xPos, yPos,
radius,
startAngle, endAngle,
anticlockwise,
lineColor, fillColor) {
var startAngle = startAngle * (Math.PI / 180);
var endAngle = endAngle * (Math.PI / 180);

var radius = radius;

context.strokeStyle = lineColor;
context.fillStyle = fillColor;
context.lineWidth = 1;

context.beginPath();
context.arc(xPos, yPos,
radius,
startAngle, endAngle,
anticlockwise);
context.fill();
context.closePath();
}

function drawLine(xStartPos, yStartPos, xEndPos, yEndPos, width, color) {
context.stokeStyle = color;
context.lineWidth = width;

context.beginPath();
context.moveTo(xStartPos, yStartPos);
context.lineTo(xEndPos, yEndPos);
context.stroke();
context.closePath();
}


JSFiddle: https://jsfiddle.net/xtkbnxx5/9/

With this version, it looks like the animation is stopping in the wrong place. However, If you comment out line 126 in the javascript and run it again, you will see that the line is just there and never gets cleared...

Any help would be greatly appreciated.

Answer

Your context.clearRect(...) statements are not clearing the entire canvas.

When I change you clearRect statements to

    context.clearRect(0,0, canvas.width, canvas.height);

Then the second line eventually disappears.

https://jsfiddle.net/xtkbnxx5/10/

Comments