Javascript canvas, unexpected error?

Hi! I'm currently developing a game with the JS canvas again. However, I'm now experiencing a drawImage bug that I've never encountered before. When I drew an image in the main loop for testing, it still wasn't drawn correctly. The code:

And although the dx and dy parameters are 100, the image is only produced so small on the canvas:

The image size itself is correct. It's a 15×15 px image that I pixelated.

The strange thing is, as soon as I set dx and dy to 500, for example, the image disappears completely and nothing is drawn anymore.

Mfg White Bread

(2 votes)
Loading...

Similar Posts

Subscribe
Notify of
8 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
BluePolicebox
1 year ago

Hello! It looks like you draw the picture before it is completely loaded. Make sure you wait for the “load” event of the image object before you sign it. Try the following code:

function update_main() {

c.clearRect(0, 0, canvas.width, canvas.height);

let img = new image();

img.src = “./media_files/images/ui_objects/start_button.png”;

img.onload = function() {

c.drawImage(img, 100, 100);

};

game.update();

game.draw();

requestAnimationFrame(update_main);

}

update_main();

By drawing the image only when it is fully loaded, you should be able to fix this problem.

BluePolicebox
1 year ago
Reply to  WeissBrot965

Maybe so? function update_main() {

c.clearRect(0, 0, canvas.width, canvas.height);

let img = new image();

img.src = “./media_files/images/ui_objects/start_button.png”;

img.onload = function() {

c.drawImage(img, 100, 100, 15, 15); // Set the desired width and height

};

game.update();

game.draw();

requestAnimationFrame(update_main);

}

update_main();

BluePolicebox
1 year ago
Reply to  WeissBrot965

What do you think?

BluePolicebox
1 year ago

Please, welcome.

regex9
1 year ago

And although the dx and dy parameters are 100, the image is only produced so small on the canvas (…)

The two parameters serve for the position indication. Not for scaling.

But the funny thing is as soon as I put dx and dy on zb 500 place the picture disappears completely (…)

Then the coordinates are already outside the character area.