meJustAndrew
meJustAndrew

Reputation: 6613

Why context stroke redraws the old drawing on canvas

Having the following example where on a canvas are drew two different lines when pressing two buttons, how can I make the second button clear the old line and draw another?

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"></canvas>

<button onclick="draw()">first</button>

<button onclick="draw2()">second</button>

<script>

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.strokeStyle = "red";

function draw(){
ctx.moveTo(0,0);
ctx.lineTo(100,200);
ctx.stroke();
}

function draw2(){
ctx.clearRect(0, 0, c.width, c.height);
ctx.moveTo(100,0);
ctx.lineTo(0,200);
ctx.stroke();
}

</script>

I am using clearRect function, to clear the canvas, but when stroke is called on the second drawing, the first one is redrawn.

Upvotes: 1

Views: 512

Answers (1)

Pointy
Pointy

Reputation: 413709

You have to call .beginPath() to clear out the current path and start a new one. In your case, it looks like you can do that at the beginning of each of your two functions.

Upvotes: 3

Related Questions