search

Home  >  Q&A  >  body text

html5 - canvas制作圆形,出来的是椭圆

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>canvas绘制时钟</title>
    <style>
        p{
            text-align: center;
            margin-top: 250px;
        }
        #clock{
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <p>
        <canvas style="width:200px ;height:200px" id="clock"></canvas>
    </p>
    <script type="text/javascript" src="js/clock.js"></script>
</body>
</html>
var dom=document.getElementById("clock");//获取canvas的id
var ctx=dom.getContext("2d");//获取上下文,HTML5不支持3d
var width=ctx.canvas.width;//
var height=ctx.canvas.height;
var r=width/2;

//定义一个方法画圆
function drawBackground(){
    ctx.save();
    //转换坐标
    ctx.translate(r,r);
    ctx.lineWidth=10;
    //获取路径
    ctx.beginPath();
    //画圆
    ctx.arc(0,0,r-5,0,2*Math.PI,false);
    //绘制当前路径
    ctx.stroke();
}
//执行方法
drawBackground();

代码如上,但是出来如下图,,,不解,,,有大神可以给解释一下吗??头一次学习canvas

迷茫迷茫2771 days ago503

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-04-17 14:30:10

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

    Change the canvas to look like this

    https://developer.mozilla.org...

    <canvas> looks very similar to the <img> element, the only difference is that it does not have src and alt attributes. In fact, the <canvas> tag has only two properties - width and height. These are optional and can also be set using DOM properties. When the width and height are not set, the canvas will initialize to a width of 300 pixels and a height of 150 pixels. The element can be sized using CSS, but the image will stretch to fit its frame dimensions when drawn: if the CSS dimensions are inconsistent with the proportions of the initial canvas, it will appear distorted.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 14:30:10

    use <canvas width="300" height="300" id="clock"></canvas> to specify the physical size of the canvas
    or `dom.width=200;
    dom.height=200;`

    and don't call it 'dom', it is a canvas element.

    reply
    0
  • Cancelreply