Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html5 canvas - does the width/height need to be defined inline?

I've been messing around with HTML5 / Javascript and found something I don't understand.

I was trying to write some basic routines for working with the HTML5 canvas, and found that the drawImage function wasn't drawing anything. Figuring it was my code, I used code from an existing tutorial, namely HTML5 Canvas Image Tutorial. When I included the Javascript code therein externally (i.e. as a separate file), I still wasn't seeing my image drawn to the canvas.

From there, I copied the complete source, found here, verbatim, and it did work. I started messing around to figure out why this worked but mine didn't.

I found that the difference was that the verbatim code defined the width and height of the canvas inline. I prefer to separate styling out of HTML and into CSS. The code worked if I did:

<canvas id = "myCanvas" width = "600" height = "400"></canvas>

but did not work if I defined the canvas width and height in an external CSS stylesheet.

I did determine that one of my problems was that I was including the stylesheet after the Javascript file; before doing that, my image did not appear at all, even after confirming via an alert() function that the code inside the image onload handler was firing. After changing the order in which the files were included, my image did appear, but was scaled weirdly, as if the CSS styling was ignored.

Why is this? Am I missing something regarding the order in which canvas properties are defined via CSS? Why does Javascript ignore the CSS styling in this case? In case it's at all relevant, I've tried this in the latest versions of both Chrome and Firefox.

like image 279
xobicvap Avatar asked Dec 03 '22 04:12

xobicvap


1 Answers

You don't have to write them there, you can write them later in JavaSript:

var can = document.getElementById('canvas1');
can.width = 600;
can.height = 400;

The defaults are 300x150 by the way.

Note that you should never, ever use CSS to define your width and height because you will be scaling the canvas instead of resizing it, causing blurriness and a loss of proportion.

like image 128
Simon Sarris Avatar answered Feb 16 '23 04:02

Simon Sarris