Getting the right width and height on you canvas

I learned something today. I was playing around with the <canvas> HTML5 element. When rendering on the canvases you do it by using the canvas’ context:

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

context.fillRect(0,0,10,10) // makes a square at (0,0) with sides 10

the unit that is used when drawing the square is dependent on the width and height property of the canvas.

So,let’s say that you do this:

canvas.width = 100;
canvas.height = 50;
context.fillRect(0,0,10,10);

On a canvas element that is styled (using css) to have width equal to height. What you’re getting is a rectangle that is more higher – since you’re filling 10 of the available 50 units (that’s 20%) of height but only 10 of the 100 units for width (10%).

By default, in Chrome, the canvas is 300×150. For the application I’m developing right now I want it to be window.innerHeight x window.innerWidth. I even wrote a converter form my “application units” and actual pixels. Looking back at this, I would have styled the canvas to full screen, then set it’s width and height in accordance to the measures of the game. Well… that’s for next time.

I still had problems getting things to work. It turned out to be a “feature” of jQuery. Look at this:

Confusing JavaScript / jQuery

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>