Bastrix
Bastrix

Reputation: 159

drawing on canvas after jquery ready

I've just started developing some small games using the HTML5 canvas tag and javascript. But as I started I found that when I call the jquery ready handler like this:

<script>$(function(){ game.init(); })</script>

And then I try to draw an image (that pre-exists in my markup) like this:

var spaceshipImg = $('#imgSpaceship')[0];
game.context.drawImage(spaceshipImg, 0, 350);

It wont work, as if the img hasn't loaded yet. However if I call this same method placing an 'onload' in my body tag, then it does work. According to jQuery documentation, all images should be loaded at this point, right?

Upvotes: 1

Views: 724

Answers (1)

Erik Schierboom
Erik Schierboom

Reputation: 16656

jQuery has two different methods for the purposes of waiting for everything to be loaded: a ready and a load method. The ready method is used when using the $(function() {}) syntax. This method does not wait for all images to be loaded though (see documentation). For that you want to use the load method. Your code would then become:

<script>
  $(window).load(function () {
    game.init();
  });
</script>

Now the init method is only called when all resources (including images) have been loaded.

Upvotes: 3

Related Questions