Binnerz92
Binnerz92

Reputation: 1

frame rate doubles on Keypress HTML Canvas JQuery

For some reason my frame rate seems to double when changing the image through a keypress. the animation works fine but they game becomes unplayable when the character has been moved so many times.

Upvotes: 0

Views: 31

Answers (1)

Kaiido
Kaiido

Reputation: 137054

This is because you are using a single <img> element, for which you change the src on keydown.

Every time the image has loaded, its load event fires, and since in this load event you do start a new animate loop, your logic goes twice has fast at each keydown, before the computer starts to loose power because of the so many loops being stacked, running all in the same frame.

An easy solution to avoid it would be to store multiple images, that you'd load only once, at initialisation.

Then, you would just have to keep track of which of these image is the one to be drawn in a variable, and update only this variable to point to one of the other images in the keydown event.

Upvotes: 1

Related Questions