moh
moh

Reputation: 443

canvas draw 2 circle inside together

im trying to draw 2 circle that are inside together

but browser draw a extra line inside second circle why?

var canvas = document.getElementById('convas');
var ctx = canvas.getContext('2d');
ctx.strokeStyle = "orange";
ctx.lineWidth = 25;
ctx.arc(160, 160, 100, 0, Math.PI * 2, false);
ctx.stroke();
ctx.moveTo(100, 100);
ctx.arc(150, 150, 40, 0, Math.PI * 2, false);
ctx.lineWidth = 20;
ctx.stroke();
<div class="center">
  <canvas id="convas" style="background: grey" width="300" height="300">
    here will go report chart if you see this text it mean your browser dont support canvas!
    so update your browser.
</canvas>
</div>

Upvotes: 0

Views: 617

Answers (1)

Kaiido
Kaiido

Reputation: 136638

This is because arc method will automatically draw the lineTo between your current x and y positions and the beginning of the arc drawing (here 100, 100.

Since arc drawing starts at 3 o'clock of the drawn arc when startAngle param is set to 0, you will want to change your moveTo(100, 100) to moveTo(arcX + arcRadius, arcY) i.e moveTo(190, 150).

var canvas = document.getElementById('convas');
var ctx = canvas.getContext('2d');
ctx.strokeStyle = "orange";
ctx.lineWidth = 25;
ctx.arc(160, 160, 100, 0, Math.PI * 2, false);
ctx.stroke();
ctx.moveTo(190, 150);
ctx.arc(150, 150, 40, 0, Math.PI * 2, false);
ctx.lineWidth = 20;
ctx.stroke();
<div class="center">
  <canvas id="convas" style="background: grey" width="300" height="300">
    here will go report chart if you see this text it mean your browser dont support canvas!
    so update your browser.
</canvas>

</div>

But you may also notice that when you call a second time stroke(), the first one is also redrawn, this time with the lineWidth set to 20.
To avoid this, call ctx.beginPath after you've drawn the first circle so that the context can know you are defining a new path, and not continuing the current one. And here, you don't even need the moveTo anymore:

var canvas = document.getElementById('convas');
var ctx = canvas.getContext('2d');
ctx.strokeStyle = "orange";
ctx.lineWidth = 25;
ctx.arc(160, 160, 100, 0, Math.PI * 2, false);
ctx.stroke();
ctx.beginPath();
ctx.arc(150, 150, 40, 0, Math.PI * 2, false);
ctx.lineWidth = 20;
ctx.stroke();
<div class="center">
  <canvas id="convas" style="background: grey" width="300" height="300">
    here will go report chart if you see this text it mean your browser dont support canvas!
    so update your browser.
</canvas>

</div>

Upvotes: 1

Related Questions