Gal Ziv Gal Ziv - 7 months ago 17
Javascript Question

Why executing Canvas.getContext('2d').arc method with exact same parameters yields different result

I execute the following code:

context.arc(100,50,50,2,3);
context.stroke();
context.arc(100,50,50,2,3);
context.stroke();


Why does the result is an arc and a closing line instead of one arc which is actually two identical arcs drawn the same way?

The parameters for the functions are its center coordinates, radius and angles.
According to that identical execution should give identical result to my understanding.

Thanks in advance

K3N K3N
Answer

This happens because there are actually three segments on the paths.

The first arc draws a sub-path like this:

http://i.imgur.com/ghX0GAJ.png

Then the path cursor is moved back to start since it has the same location as the first arc, and in the process it will create a line since all paths are currently connected:

http://i.imgur.com/t736ylM.png

To avoid it you can break up the sub-path by creating a new one by using moveTo() and move the cursor to the position the next arc will start, or simply clear the current path and start a new:

Example

var context = c.getContext("2d");
context.arc(100,50,50,2,3);
context.stroke();
context.beginPath();
context.arc(100,50,50,2,3);
context.stroke();
<canvas id=c></canvas>

http://i.imgur.com/R2kuaKH.png

To use moveTo() you would have to calculate the angle using:

centerX + cos(angle) x radius
centerY + sin(angle) x radius

Example

var context = c.getContext("2d");
context.arc(100,50,50,2,3);
context.stroke();
context.moveTo(100 + Math.cos(2) * 50, 50 + Math.sin(2) * 50);
context.arc(100,50,50,2,3);
context.stroke();
<canvas id=c></canvas>

Comments