Why is my canvas image looking all scaled? (HTML5)

If you are doing some drawing with the canvas and you find your images getting scaled even if you swear you didn’t set the .scale property (JawsJS, EaselJS) then allow me to show you, my imaginary reader, the crazy magic that could be causing it.

Canvas and CSS

Canvas is just a place for you to put bitmap data. Its 2 attributes, height and width controls how many pixels the canvas contains. So this:

<canvas width="240" height="240"></canvas>

just initializes a 240×240 bitmap data. The canvas keeps that data and does whatever it wants with it. The rest of the DOM can’t do anything with that data.

CSS is where you tell the browser how the DOM should be rendered. Its primary purpose is laying out your DOM to make it look cool. So what happens if you set the css height and width of a canvas?

<canvas width="240" height="240"></canvas>

<canvas width="240" height="240" style="width: 480px; height: 480px"><canvas>

Here’s how CSS and Canvas negotiates their renderings: the CSS asks the canvas for the bitmap data so he can render it. The canvas shows her bitmap data. CSS turns the bitmap data into pixels based on the CSS rules he was given. “Hmm.. canvas says she has 240×240 bits of data, but my orders are to draw them in 480×480 pixels. This means 1 bit data is equal to 2×2 pixels. Cool, I’ll tell the browser about this.”

CSS tells the browser that he’s got all the layouts done and browser can now go and draw it on the screen. And that is why your canvas is all scaled and shit.

More boring explanation here

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: