从一张图上截取不同图块,动态显示在canvas上,形成赛跑的效果。完整代码图片下载请点击 https://files.cnblogs.com/files/xiandedanteng/turtleSheepRace.rar:
<!DOCTYPE html> <html lang="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <head> <title>龟羊赛跑</title> </head> <body onload="draw()"> <canvas id="myCanvus" width="1000px" height="150px" style="border:1px dashed black;"> 出现文字表示你的浏览器不支持HTML5 </canvas> </body> </html> <script type="text/javascript"> <!-- function draw(){ var canvas=document.getElementById('myCanvus'); canvas.width=1000; canvas.height=150; var context=canvas.getContext('2d'); var img=new Image(); img.src="walkingAnimals.jpg"; // 乌龟图块坐标 var turtleCds=[ {'x':'10','y':'10','width':'110','height':'80'}, {'x':'120','y':'10','width':'110','height':'80'}, {'x':'230','y':'10','width':'110','height':'80'}, {'x':'340','y':'10','width':'110','height':'80'}, ]; // 绵羊图块坐标 var sheepCds=[ {'x':'10','y':'100','width':'110','height':'100'}, {'x':'120','y':'100','width':'100','height':'100'}, {'x':'224','y':'100','width':'110','height':'100'}, {'x':'330','y':'100','width':'110','height':'100'}, ]; loop=setInterval(function(){ run(context,img,turtleCds,sheepCds); }, 100); }; var turtleSpeed=-80; var sheepSpeed=-100; var i=0; function run(context,img,turtleCds,sheepCds){ context.clearRect(0,0,1000,150);// clearScreen context.strokeStyle = "black"; turtleSpeed++; if(turtleSpeed-80>1000){ turtleSpeed=-80; } i=turtleSpeed % 4; sheepSpeed+=1.5; if(sheepSpeed-100>1000){ sheepSpeed=-100; } // 截取一块图贴上 context.drawImage(img,turtleCds[i].x,turtleCds[i].y,turtleCds[i].width,turtleCds[i].height,turtleSpeed,50,turtleCds[i].width,turtleCds[i].height); context.drawImage(img,sheepCds[i].x,sheepCds[i].y,sheepCds[i].width,sheepCds[i].height,sheepSpeed,50,sheepCds[i].width,sheepCds[i].height); } //--> </script>