Reputation: 37
I just finished my first JavaScript book, "Head First HTML5", and I'm feeling quite dumb. If i put the script in the HTML file it works, but doesn't work in a separate JavaScript file.
HTML file:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<script src="canArt.js"></script>
</head>
<body>
<canvas id="canvas" width="800" height="800"></canvas>
</body>
</head>
JS file:
window.onload = init();
function init() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (30, 30, 55, 50);
}
please help.
Upvotes: 0
Views: 1018
Reputation: 35409
Your immediately executing the init
function by including the parens and assigning the result of init
, which is nothing, to the onload
handler...
change:
window.onload = init();
to:
window.onload = init;
Upvotes: 3