最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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>

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>

Share Improve this question asked Jan 17, 2014 at 7:02 exebookexebook 33.9k40 gold badges151 silver badges241 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 27

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.

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论