wong2
wong2

Reputation: 35700

Canvas can't draw a square?

    <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 :
enter image description here

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

Upvotes: 8

Views: 6437

Answers (2)

Fedor Skrynnikov
Fedor Skrynnikov

Reputation: 5609

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 :)

Upvotes: 1

dknaack
dknaack

Reputation: 60438

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>  

Upvotes: 19

Related Questions