Zydnar
Zydnar

Reputation: 1502

How to draw in canvas 2D this shape and fill it with color?

canvas 2D

This should be without this diagonal. I want to draw two arcs one with x2 smaller radius, join them and fill(). I know how to calculate the end and beginning of an arc, problem is arcs are always drawn clockwise, so to draw second arc within same ctx.beginPath() I have to use something like ctx.moveTo() but problem with moveTo is I get two different paths as proof closePath() cause this diagonal.

So I want to know how to draw arc in other direction than clockwise or how to use moveTo() but still beeing able to fill this shape. Filling now cause following issue: enter image description here White diagonal visible.

Upvotes: 3

Views: 1029

Answers (2)

ibrahim mahrir
ibrahim mahrir

Reputation: 31682

Why not use the lineWidth property to make the arc thicker. In this case you'll only need one call to arc:

let canvas = document.getElementById("canvas"),
    context = canvas.getContext("2d");
    
    
context.beginPath();
context.arc(20, 20, 40, 0, Math.PI / 4);
context.lineWidth = 15;
context.stroke();
<canvas id="canvas"></canvas>

Upvotes: 2

Alnitak
Alnitak

Reputation: 339786

Arcs are not always drawn clockwise. The sixth parameter to .arc is a boolean which when true will make the arc be drawn anti-clockwise.

However you will also need to reverse the start and end angles, otherwise the arc will attempt to go the long way around:

var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.arc(20, 20, 40, 30 * Math.PI / 180, 80 * Math.PI / 180);
ctx.arc(20, 20, 150, 80 * Math.PI / 180, 30 * Math.PI / 180, true);
ctx.closePath();

ctx.lineWidth = 3;
ctx.stroke();
ctx.fillStyle = '#e0e0ff';
ctx.fill();
<canvas id="c" width="200" height="200" />

Upvotes: 5

Related Questions