How to make Canvas Arcs having sharp angled arcs

Viewed 60

So for some reason I could sworn this was how arc always worked in the canvas tag, but unfortunately it doesn't.

So what I expected and eventually want to have as the end result is this:

canvas.arc(x,y,r,0,360); //ik this should be Math.PI * 2 
canvas.arc(x,y,r,0,270); //and other Math.PI * #
canvas.arc(x,y,r,0,180); //But I used degrees to help show
canvas.arc(x,y,r,0,90);  //how I'd like it to use it.

And it will make these circles:

enter image description here

But unfortunely it does something way different, when you do the above code... It creates the STROKE part of the circle just fine, but filling it in just draws a line from start angle to end angle and fills it:

enter image description here

The only solution I can think of is to somehow overide the filling process of the arc to instead of lineTo the other angle, first lineTo the center of the arc then back to the end angle. But I have no idea how todo that, and I also don't understand beizers enough to try to recreate the arc from scratch so it using my desired lineTo usage.

To summary: How do I make my filled circles have actual "angles" in the center of the partial circle?

1 Answers

Circles in the canvas can be tough to wrap your head around at first, but there's a fairly simple solution to this one:

ctx.lineTo();

The problem is not with the fill() method but rather how you are drawing the stroke.

Here's how I'd do it:

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.arc(50, 50, 50, Math.PI, Math.PI * 1.5, false);
ctx.lineTo(50, 50);
ctx.closePath();
ctx.fill();
<canvas width="100" height="100"></canvas>

To explain, once you finish drawing the arc, simply drawing a line from one end of the curve to the center of the circle should do the trick! This is because the fill method fills everything strictly from endpoint to endpoint. This method of drawing a line to the center should technically work with any variant of partial circles.

Related