exebook
exebook

Reputation: 33900

Canvas: arc(75,75,50,0,3.1415,true) draws oval instead of circle

Why this code draws oval instead of circle at the position (75, 75) with the radius 50?

<canvas id=c1 style="width:400;height:400">
<script>
    ctx = c1.getContext('2d');
    ctx.fillStyle = '#7ef';
    ctx.fillRect(0, 0, 400, 400);
    ctx.fillStyle = '#000';
    ctx.beginPath();
    ctx.arc(75,75,50,0,Math.PI*2,true)
    ctx.stroke();
</script>

enter image description here

Upvotes: 9

Views: 3631

Answers (2)

user1693593
user1693593

Reputation:

If you change this line:

<canvas id=c1 style="width:400;height:400">

to:

<canvas id=c1 width=400 height=400></canvas>

it should work. Don't use CSS to set Canvas sizes as this only affects the element but not the bitmap itself. For canvas you need to use it's dedicated properties (width/height) to also set the bitmap size or the bitmap is just stretched/scaled to match the size of the element.

The default size of canvas if not specified is 300x150 pixels. In this case those pixels are stretched (as an image) to 400x400 which is why you get an oval instead.

Upvotes: 27

Mr. TA
Mr. TA

Reputation: 5359

In cases where the size of the canvas is dynamic and not known at development time, you can set the size using JavaScript when you know that the browser has already positioned and sized the element appropriately:

canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;

This is useful when developing for mobile either as a website or a PhoneGap/Cordova app.

Upvotes: 6

Related Questions