I'm making a canvas webpage for animation. Strange thing is that every time I launch the webpage from double clicking the html file the canvas will almost always size incorrectly. I have post a similar question before: Canvas sizing incorrectly on loading but have no desired answer.
After extensive debugging I find out that it's the window.innerWidth that's giving me such trouble. The window.innerWidth returns 0 every time the page is launched from double clicking the html file and results in a incorrect canvas size (interestingly the canvas size is not exactly 0, but a very small one that has object to be rendered stack on top of one another), but after reloading the page (Ctrl+R) the problem no longer happens. I'm using jQuery to load the page, here is my code:
html:
<body>
<canvas id="main_canvas"></canvas>
</body>
js:
$(document).ready(function() {
var SCREEN_WIDTH = window.innerWidth-10,
SCREEN_HEIGHT = window.innerHeight-10;
if (window.innerWidth === 0) { alert("wtf? width = 0?");}
var canvas = $('canvas')[0],
context;
init(); // use $(window).load(init) does not fix the problem
function init() {
if (canvas.getContext) {
context = canvas.getContext('2d');
animate(); // draw stuff
}
else {
alert('Your browser does not support html5 canvas');
}
}
});
As you can see here, I'm already using $(docuemnt).ready(function()) to make sure things gets loaded, however from a link http://4loc.wordpress.com/2009/04/28/documentready-vs-windowload/ the author suggest that the document ready event executes already when the HTML-Document is loaded and the DOM is ready, even if all the graphics haven’t loaded yet.
On the other hand the $(window).load(function()) executes a bit later when the complete page is fully loaded, including all frames, objects and images. Therefore functions which concern images or other page contents should be placed in the load event for the window or the content tag itself. But even I use this the problem is not solved.
Maybe the js file is asking for window's width before it's loaded, but I can't find a viable solution. Can anyone help with this?