My images won't load in canvas.

I wanted to try my hand at making a game using JS. The games main loop seems to be running the array names images has the file path to the source material how ever I can't figure out how to get them to display. This is the JS file http://pastebin.com/m21D5Pz5 and the html <!DOCTYPE html>

<head> <link href='http://fonts.googleapis.com/css?family=Covered+By+Your+Grace' rel='stylesheet' type='text/css'> <link href='ooop.css' rel='stylesheet' type='text/css'> </head> <body> <div id="wrapper"> <div id="banner"> <h1 id="title">#OfficeOfOldPeople</h1> </div> <div class="content">
	<canvas id="c1" width="600" height="600"></canvas><br />
	<script src="test.js">
	game.run();</script>
	
</div>
<div class="footer">
</div>
</div> </body> </html5>

Can some one tell me what I am doing wrong?

Posted Dec 16, 2014, 2:22 PM UTC

35
jotted•

Functions and properties are case-sensitive. When images load, they check for an onload function and execute that - but you've defined onLoad, not onload.

2
LastByteOP•

I tried both. Neither will work :(

1
jotted•

OK, so there's a couple more problems, but they're pretty minor except for this scope issue.

The good news is that your image loader basically works.

You main issue is that your onload functions are defined in a for loop, but for loops don't have a scope.

When each image fires its onload function, it will be using the value of variable i. The for loop has probably long finished by this point, so every image will be looking for images[4] ( i is iterated at the end of the last loop).

To fix this, we just have to use your onload function differently. A LoadEvent, like other Events, pass the Event object as the first argument. If we name that, we can access the event's target property, which should be the img element:

images[i].onload = function(evt){
    ctx.drawImage(evt.target, ....etc );
}

Your browser's developer tools will really help you. If you put the statement debugger; in your code somewhere, you can step over each instruction and see how your variables change.

2
LastByteOP•

Thank you! It works now :)

1
temp0044476•

Are the images on your own computer? Because you can't load images, files, etc, from your own computer, unless you have a webserver running on it and get them from the webserver directory.

Temporary workaround in Firefox - set security.fileuri.strict_origin_policy to false. But remember to change it back to true after you're done testing your program.

1