Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 698
wong2 Avatar asked Jul 20 '11 06:07

wong2


People also ask

Which method draws a rectangle on canvas?

The rect() method creates a rectangle. Tip: Use the stroke() or the fill() method to actually draw the rectangle on the canvas.

How do you add a rectangle to a canvas?

To draw the rectangle onto a canvas, you can use the fill() or stroke() methods. Note: To both create and render a rectangle in one step, use the fillRect() or strokeRect() methods.

Which method is used to draw a circle on a canvas?

To draw arcs or circles, we use the arc() or arcTo() methods.

What property will one use to know whether Canvas is supported?

The cast result can be used to check whether HTML5 canvas is supported in the browser.


2 Answers

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>  
like image 150
dknaack Avatar answered Sep 19 '22 12:09

dknaack


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

like image 41
Fedor Skrynnikov Avatar answered Sep 22 '22 12:09

Fedor Skrynnikov