javascript - I made an h5 canvas game, using requestanimation to control direction movement, and keys to control whether to press the direction keys, but it's a bit stuck. Could you please tell me how to optimize it?
过去多啦不再A梦
2017-07-05 10:56:06
I can’t type out the specific code. Is there any expert who can provide valuable advice?
Change animation in frames to animation in time
For pictures that do not need to be changed frequently, such as backgrounds, etc., please use off-screen canvas
For some details, such as canvas.width, etc., you need to use width = canvas.width to save the value
Use function throttling
The event-triggered action should not be based on the bound function. The trigger parameters need to be passed into the program and implemented through the game loop. For example: when clicking the right arrow, you only need to tell the game body that moving to the right has been triggered, and the program determines how to move.
Optimize the loop. Generally speaking, the main reason for the slow running of the program is this. There is too much internal logic and there is no time to process it in a unit loop. For some data calculation things, such as generating random numbers, etc., you can Worker is used to implement it. For some functions that do not need to be used frequently, please try to avoid calling them. Only call them after certain situations are triggered and the parameter values change. For example, if(go) dosomething(); only operates when go is true, which can save a lot of time.
Of course, the specific optimization details need to be determined according to your code. I can only talk about these general things. In fact, most optimization ideas are the same
It may be a problem with event registration. You can start with event delegation and cancel the event after the dom is finished.
You can use chrome devtool to open the profile and check the cpu and memory to see if any functions have leaks or other problems.
Use partial refresh of canvas instead of refreshing the entire screen every time you move it
Did you write the game using DOM? Or use CANVAS