<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/
The rect() method creates a rectangle. Tip: Use the stroke() or the fill() method to actually draw the rectangle on the 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.
To draw arcs or circles, we use the arc() or arcTo() methods.
The cast result can be used to check whether HTML5 canvas is supported in the browser.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With