How to fill different colors for circles on canvas?

Member

by aubrey , in category: Javascript , 5 months ago

How to fill different colors for circles on canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 5 months ago

@aubrey 

To fill different colors for circles on a canvas in HTML5, you can use the Canvas API to draw circles and set different fill colors. Here's an example code snippet that demonstrates how to fill circles with different colors on a canvas:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!DOCTYPE html>
<html>
<head>
    <title>Canvas Circles</title>
</head>
<body>

<canvas id="myCanvas" width="200" height="200"></canvas>

<script>
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');

    // Draw a red circle
    ctx.beginPath();
    ctx.arc(100, 100, 50, 0, 2*Math.PI);
    ctx.fillStyle = 'red';
    ctx.fill();

    // Draw a blue circle
    ctx.beginPath();
    ctx.arc(50, 50, 25, 0, 2*Math.PI);
    ctx.fillStyle = 'blue';
    ctx.fill();

    // Draw a green circle
    ctx.beginPath();
    ctx.arc(150, 150, 30, 0, 2*Math.PI);
    ctx.fillStyle = 'green';
    ctx.fill();
</script>

</body>
</html>


In this code, we first create a canvas element with id="myCanvas". We then use JavaScript to get the canvas element and its 2D rendering context. We use the context's beginPath() method to start drawing a new shape, arc() method to draw a circle, and fillStyle property to set the fill color. Finally, we call the fill() method to fill the circle with the specified color.


You can customize this code snippet by changing the circle positions, radii, and fill colors to create different colored circles on the canvas.