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
  • 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
    Commented Jan 7, 2017 at 11:57

1 Answer 1

2
\$\begingroup\$

You should use this (literally):

var campfire = new Image();
campfire.onload = function () {
    ctx.drawImage(this, campfireX, campfireY);
};
campfire.src = "Sprites/Campfire.png";
\$\endgroup\$
10
  • \$\begingroup\$ I don't think it worked, when I tried it, the campfire still didn't show \$\endgroup\$ Commented Jan 9, 2017 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\$ Commented Jan 9, 2017 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\$ Commented Jan 9, 2017 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\$ Commented Jan 10, 2017 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\$ Commented Jan 13, 2017 at 18:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .