-33 Votes

HTML5 Canvas: Draw filled Circle

Question by PC Control | 2014-05-22 at 16:58

On the Internet, I have found a code with which it is possible to draw a circle on an HTML 5 canvas.

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
 
context.beginPath();
context.arc(100, 100, 50, 0, 2*Math.PI);
context.stroke();

The code above is drawing a circle at the point 100/100 having a radius of 50 pixel. This is working so far.

However, only the border of the circle is drawn using this code. Though, I would rather want to have a filled circle and not only the surrounding. Is that possible, too?

ReplyPositiveNegative
3Best Answer3 Votes

When enhancing your example in the following way, you can specify the color for the border and the filling:

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
 
context.beginPath();
context.arc(100, 100, 50, 0, 2*Math.PI);
context.strokeStyle = '#000000';
context.stroke();
context.fillStyle = '#FF0000';
context.fill();

Using this code, it is important to know that fill() is caring about the filling and stroke() is making the border line.

First, you are defining a path with arc(). This path remains invisible at this moment.

Only with calling stroke(), the border is drawn. How it is drawn is defined with the property strokeStyle before. Here, we have just set strokeStyle to the color #000000 (black), so that stroke() will draw a black border.

With fill(), the situation is similar. First of all, we are setting the fillStyle to #FF0000 (red) and after that, we are calling fill(). With this, the current defined path will be filled with the recent fillStyle and the circle will have a red colored filling.

If we only want to draw the border or the filling, accordingly, we can omit calling stroke() or fill().
2014-05-22 at 17:39

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.