This problem seems to be common, though I couldn't find the answer.
I've got this simple html with the only canvas tag
<!doctype html>
<head>
<meta charset = "utf-8">
<script src="js/script.js"></script>
<title>Title</title>
</head>
<body>
<canvas id = "canvas"></canvas>
</body>
</html>
and in script.js I'm trying to catch window.onload event:
window.onload = init;
function init(){
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillRect(50, 20, 150, 150);
}
But nothing happens. I assume that the html is loaded even before the first line of js executed.
So I found that the alternative to onload event would be to put script definition in the end of the body, so when script being executed the window is supposed to be loaded alreade. So I did like this:
<!doctype html>
<head>
<meta charset = "utf-8">
<!-- gone -->
<title>Title</title>
</head>
<body>
<canvas id = "canvas"></canvas>
<script src="js/script.js"></script> <!-- inserted -->
</body>
</html>
and
<!-- window.onload = init; -->
init() <!-- inserted -->
function init(){
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillRect(50, 20, 150, 150);
}
And in a way it works (draws rectangle) , but gives me an error Uncaught ReferenceError: context is not defined.
So my question is what I'm doing wrong? I'm also wonderring if there is a better way to do this.
P.S. I tend not to use jquery...
EDITED: the error with context has nothing to do with the code above, although I still don't like the idea of putting the link to js file in the end of the body...