WannaBDeveloper
WannaBDeveloper

Reputation: 146

HTML 5 Canvas and Draw Circle

I am trying to understand why my circle is not in the middle of my Canvas in HTML 5. I am trying to create a circle in the middle the canvas.

The canvas is as follows:

Canvas: Width: 600 Height: 300

Then I draw a circle with the following code:

context.beginPath();
context.fillStyle = '#424';
context.arc(300, 150, 10, 0, 2*Math.PI, false);
context.fill();
context.closePath();

The circle is drawn inthe lower right corner.

Now if I change the (x, y) to (150, 75) then it shows in the middle.

I am just hoping someone can shed a little light on why the original code doesn't work.

Upvotes: 3

Views: 6381

Answers (1)

user1693593
user1693593

Reputation:

You are not showing how you are setting the actual width and height of the canvas, but if the center point always is 150, 75 then the canvas is always at default size which means you are probably setting the size using css instead of directly on the element.

Try something like this:

<canvas id="myCanvas" width=600 height=300></canvas>

in JavaScript:

canvas.width = 600;   // don't use canvas.style.*
canvas.height = 300;

You could also set the center this way for the arc (to make it adopt center automatically):

context.arc(context.canvas.width * 0.5, context.canvas.height * 0.5,
            10, 0, 2*Math.PI, false);

Upvotes: 1

Related Questions