<!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="-1" /> <meta http-equiv="Cache-Control" content="no-cache" /> <title>My first Game</title> <style type="text/css"> body { border:none 0px; margin:0px; padding:10px; font-size : 16px; background-color : #f3f3f3; } canvas { border : 1px solid blue; } </style> <script type="text/javascript"> function loadImage(imglist,callback){ var imgs = {}; var count = imglist.length; var loadedcount = 0; for(var i=0; i<count; i++){ var img = imglist[i]; var image = imgs[img.id] = new Image(); image.src = img.url; image.onload = function(evt){ loadedcount++; } } if(typeof callback == "function"){ var t = this; function check(){ if(loadedcount >= count){ callback.apply(t,arguments); } else{ setTimeout(check,100); } } check(); } return imgs; } var imgcache = null; var canvas = null; var context = null; function init(){ canvas = document.createElement("canvas"); canvas.width = 600; canvas.height = 400; document.body.appendChild(canvas); context = canvas.getContext("2d"); var imgs = [ {id:"player",url:"../res/player.png"}, {id:"bg",url:"../res/bg.png"} ]; imgcache = loadImage(imgs,startDemo); }; function startDemo(){ var fps=30; var sleep = Math.floor(1000/fps);//每秒循环30次(动画的肉眼效果每秒30针就能流畅的播放) var img = imgcache["player"]; //初始坐标 var x=0,y=284; //移动速度 var speedx = 65/1000, speedy = -45/1000;//每秒往 x 正方向移动65px, y 反方向移动45px var minx=0,maxx=500,miny=0,maxy=284; var mainloop = setInterval(function(){ var deltatime = sleep; //每次循环,改变一下绘制的坐标. x = x+speedx*deltatime;//向右移动 y = y+speedy*deltatime;//向上移动 就是top值 在减少 //限定移动范围 x = Math.max(minx,Math.min(x,maxx)); y = Math.max(miny,Math.min(y,maxy)); context.drawImage(imgcache["bg"],0,0);//使用背景覆盖的方式 清空之前绘制的图片 var sx=0,sy=60,sw=50,sh=60; context.drawImage(img,sx,sy,sw,sh,Math.floor(x),Math.floor(y),sw,sh); },sleep); }; </script> </head> <body onload="init()"> </body> </html>
思路很简单 使用setInterval 不停的去改变 图片的位置
值得注意的是 每次都需要清空背景图片