Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas javascript clear path

Tags:

html5-canvas

I am testing out a little Canvas programming and I have a question about how to clear previous paths when drawing a new one.

Example: Paint a filled circle with no stroke and a stroked line. I have the following code:

graphicContext.save();
graphicContext.beginPath();
graphicContext.arc(95,50,40,0,2*Math.PI);
graphicContext.fillStyle="rgb(50, 200, 200)";
graphicContext.fill();
graphicContext.restore();

graphicContext.save();
graphicContext.moveTo(0,0);
graphicContext.lineTo(200,100);
graphicContext.stroke();
graphicContext.restore();

However, both the circle and the line are stroked. How can I stroke the line without also stroking the circle?

like image 823
user1660218 Avatar asked Oct 16 '25 14:10

user1660218


1 Answers

First of all, there is no need to use save and restore method.

Second, use beginPath method before drawing the line, as you are creating a new path. beginPath will reset / clear the previous path ...

var graphicContext = document.querySelector('#canvas').getContext('2d')

// circle
graphicContext.beginPath();
graphicContext.arc(95,50,40,0,2*Math.PI);
graphicContext.fillStyle="rgb(50, 200, 200)";
graphicContext.fill();

// line
graphicContext.beginPath();
graphicContext.moveTo(0,0);
graphicContext.lineTo(200,100);
graphicContext.stroke();
<canvas id="canvas"></canvas>
like image 103
ɢʀᴜɴᴛ Avatar answered Oct 19 '25 13:10

ɢʀᴜɴᴛ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!