Categories
JavaScript Answers

How to add different fillStyle colors for arc in canvas with JavaScript?

Spread the love

Sometimes, we want to add different fillStyle colors for arc in canvas with JavaScript.

In this article, we’ll look at how to add different fillStyle colors for arc in canvas with JavaScript.

How to add different fillStyle colors for arc in canvas with JavaScript?

To add different fillStyle colors for arc in canvas with JavaScript, we can draw 2 different arcs.

For instance, we write:

<canvas width='400' height='400'></canvas>

to add a canvas element.

Then we write:

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(15, 15, 15, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();

ctx.fillStyle = "green";
ctx.beginPath();
ctx.arc(100, 15, 15, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();

We select the canvas with querySelector.

Then we call getContext to get the context.

Next, we set the fillStyle for the arc.

Then we call arc with the coordinates of the top left corner, radius, start and end angle, and whether we want to draw counterclockwise respectively.

We call closePath and fill to draw and fill the arc respectively.

Likewise, we draw the 2nd arc the same way but with different fillStyle.

Now we see a red and green circle drawn.

Conclusion

To add different fillStyle colors for arc in canvas with JavaScript, we can draw 2 different arcs.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *