简体   繁体   中英

html 5 canvas: using draw image in game makes loop very slow

i am making a game based on draw images and clear it every some part of second. i started with:

var peng = new Image();

and then :

  peng.onload = function() {
context.drawImage(peng, pengXPosition, pengYPosition, pengWidth, pengHight);
};

and in the loop :

var i=0;
function pengMoveRight(){ i++;if(i==1){peng.src = 'images/1.png';}else if(i==2)
       {peng.src = 'images/2.png';} else if(i==3){peng.src = 'images/3.png';}else if(i==4){
        peng.src = 'images/4.png';}else if(i==5){peng.src = 'images/5.png';}else if(i==6){
        peng.src = 'images/6.png';i-=6;}}

when i run it it works well on IE but on chrome and mozilla it`s too slow and the character is about to disappear .. i used setinterval(); once and window.requestAnimationFrame(); once and both of them cause the same problem. what should i do to make it smooth move? here is the full script http://mark-tec.com/custom%20game/

Instead of changing the source, try to create several Image objects instead. That way, the drawImage call can always use a pre-loaded image.

You need to preload all the images or use the sprite method (all images packed into a single sprite) in order to avoid the initial delay caused by the image loading only when it's needed.

However, after that initial problem, your example should run fine once all the images are cached.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM