0
\$\begingroup\$

In my game at the beginning the first thing that you'll see is a campfire with this code:

 var campfire = new Image();
   campfire.onload = function () {
      ctx.drawImage(campfire, campfireX, campfireY);
 };
 campfire.src = "Sprites/Campfire.png";

However, it doesn't work, I put an

alert("All systems a-ok");

at the end and i get the alert so i don't understand why it's there. You can find the actual image file here and the full code here. Sorry if I didn't format this well or something, I'm not very good at this =3

This may seem similar to an older question of mine in which I stated how to add a sprite onto the canvas, though in this case, I'm asking why the image doesn't appear on the canvas at all, even though there's no errors.

\$\endgroup\$
  • 1
    \$\begingroup\$ The reason you see your alert even if the image didn't load is because onload is a callback function. Put your alert inside that function. Use the dev tools in your browser to debug this. In this case prefer console.log('loaded'); over alert to avoid having to click the alert. \$\endgroup\$ – Neil Jan 7 '17 at 11:57
1
\$\begingroup\$

You should use this (literally):

var campfire = new Image();
campfire.onload = function () {
    ctx.drawImage(this, campfireX, campfireY);
};
campfire.src = "Sprites/Campfire.png";
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I don't think it worked, when I tried it, the campfire still didn't show \$\endgroup\$ – The Gamer King Jan 9 '17 at 13:13
  • \$\begingroup\$ That's weird, thought this would work. btw I know this is a little late but what about using an engine like phaser. Or something even leaner like Playgroundjs \$\endgroup\$ – Kitanga Nday Jan 9 '17 at 19:19
  • \$\begingroup\$ It'll cost you a lot less heartache later to switch from your own engine to one that's already been battle tested. Trust me on this. I also had that "I'll use my own engine" pride. But ended up regretting it. Check out this link for some really neat options and more resources. \$\endgroup\$ – Kitanga Nday Jan 9 '17 at 19:22
  • \$\begingroup\$ I would, but I'm too far into the game, if I stop now I'll have a couple months worth of work destroyed \$\endgroup\$ – The Gamer King Jan 10 '17 at 20:57
  • 1
    \$\begingroup\$ Try moving your game to an engine like phaser in a week and see how you move through the features. Compare it to you working with your custom engine, and I'm certain those features were faster to implement in the engine (e.g. phaser) than in your custom engine. \$\endgroup\$ – Kitanga Nday Jan 13 '17 at 18:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.