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

javascript - Canvas can't draw a square? - Stack Overflow

programmeradmin0浏览0评论
    <canvas id="c" style="border: solid 1px black; width: 300px; height: 300px;"></canvas> 
    <script type="text/javascript">
        var canvas = document.getElementById("c"),
        ctx = canvas.getContext("2d");
        ctx.fillRect(0, 0, 50, 50);
    </script>  

Result in :

fiddle: /

    <canvas id="c" style="border: solid 1px black; width: 300px; height: 300px;"></canvas> 
    <script type="text/javascript">
        var canvas = document.getElementById("c"),
        ctx = canvas.getContext("2d");
        ctx.fillRect(0, 0, 50, 50);
    </script>  

Result in :

fiddle: http://jsfiddle.net/wong2/xZGUj/

Share Improve this question asked Jul 20, 2011 at 6:31 wong2wong2 35.7k51 gold badges137 silver badges182 bronze badges 1
  • 2 possible duplicate of drawImage on canvas has weird aspect ratio in firefox and other problems – Tatu Ulmanen Commented Jul 20, 2011 at 6:34
Add a comment  | 

2 Answers 2

Reset to default 19

The problem is the style attribute of the canvas.

Setting the size of the canvas using the style attribute will result in scaling issues. This happens cause the canvas element has a default size. If you set the size using css it differs from that size => scaling issues. You can alert(canvas.height) and you will see that it has a value, even if you dont set one.

If you change to the following it will work:

<canvas id="c" width="100" height="100" style="border: solid 1px black;"></canvas> 
<script type="text/javascript">
    var canvas = document.getElementById("c"),
    ctx = canvas.getContext("2d");
    ctx.fillRect(0, 0, 50, 50);
</script>  

it can you should put width and height as attributes of canvas Check this out http://jsfiddle.net/Fedor/xZGUj/3/

I guess, attributes width and height initialize coordinate system insight canvas. css properties only limit the size of your canvas. So when you don't specify width and heihgt you will get coordinate system in width=300 and height=150 by default. You may find this information here http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#attr-canvas-width

So if you in your fiddle put height in css 150...squre will be squre :)

发布评论

评论列表(0)

  1. 暂无评论