0

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.

1 Answer 1

3

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;

http://jsfiddle.net/sFmNw/

Sign up to request clarification or add additional context in comments.

1 Comment

In other words, saying = init(); executes the init function immediately and assigns its return value to window.onload, while saying = init; assigns the function itself as the onload handler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.