來到系列第三篇,我們要挑戰更有趣的精靈圖(Sprite)動畫。做法是將角色的多個動作幀拼在一張大圖上,再透過 drawImage 即時裁切出目前該顯示的那一幀,從而形成走路、轉身的效果。這正是許多 2D 遊戲角色的經典實作方式。
本例中的角色會在畫布左右來回走動:朝左時只播放第 0、1、2 幀,朝右時則播放第 3、4、5 幀;碰到邊緣時自動轉向並切換幀組。你還可以透過輸入框調整幀數、速度與縮放比例,觀察動畫的變化。
<canvas id="canvas3" width="250" height="300" style="background-color:black">
你的瀏覽器不支援 <canvas>標籤,請使用 Chrome 瀏覽器 或者 Firefox 瀏覽器
</canvas><br/>
幀數:<input id="txt4" type="text" value="10"/><br/>
速度:<input type="text" id="txt5" value="5"/><br/>
比例:<input type="text" id="txt6" value="2"/><br/>
<input type="button" value="開始" onclick="animate()"/>
<input type="button" value="暫停" onclick="stop()"/>
<script type="text/Javascript">
//定時器
var interval=null;
//停止動畫
function stop(){
clearInterval(interval);
}
//===================================================================
//精靈登場
//====================================================================
//每一幀在大圖中的位置
var frames=[];
frames[0]=[0,4,19,19];
frames[1]=[22,1,24,19];
frames[2]=[49,0,18,17];
frames[3]=[1,32,18,17];
frames[4]=[22,33,24,19];
frames[5]=[49,36,19,19];
//精靈類
function Sprite(dx,dy,delta,fps){
this.dx=dx;
this.dy=dy;
this.fps=fps;
this.delay=1000/fps;
this.last_update=0;
//移動速度
this.delta=-delta;
//幀編號
this.index=0;
//方向
this.dir_left=true;
}
Sprite.prototype.update=function(canvas){
//獲取當前時間
var now=(new Date()).getTime();
if((now-this.last_update)>this.delay){
if(this.dir_left){
//方向朝左,只繪制0 1 2幀
if(this.index>2)
this.index=0;
}
else{
//方向朝右,只繪制 3 4 5 幀
if(this.index>5)
this.index=3;
}
//取出當前幀的坐標
this.frame=frames[this.index];
//當前幀在大圖中的位置
this.sx=this.frame[0];
this.sy=this.frame[1];
this.sw=this.frame[2];
this.sh=this.frame[3];
//當前幀大小
this.dw=this.frame[2];
this.dh=this.frame[3];
//改變 x 坐標
this.dx=this.dx+this.delta;
//左邊緣檢測
if(this.dx<0){
this.dx=0;
//轉向
this.delta=-this.delta;
this.dir_left=false;
this.index=3;
}
//右邊緣檢測
if((this.dx+this.dw)>canvas.getAttribute("width")){
this.dx=canvas.getAttribute("width")-this.dw;
//轉向
this.delta=-this.delta;
this.dir_left=true;
this.index=0;
}
this.dy=this.dy;//y 不移動
this.index++;
this.last_update=now;
}
}
function animate(){
//停止動畫
stop();
//移動速度
var delta=parseInt(document.getElementById('txt4').value);
//每秒繪制多少次
var fps=parseInt(document.getElementById('txt5').value);
//比例
var scale=parseInt(document.getElementById('txt6').value);
//畫布對象
var canvas=document.getElementById("canvas3")
//獲取上下文對象
var ctx = canvas.getContext("2d");
//清空畫布
ctx.clearRect(0,0,canvas.getAttribute("width"),canvas.getAttribute("height"));
var img=new Image();
img.src="https://www.crazyfrom.com/images/2010/10/sprite.gif";
var sprite=new Sprite(120,150,delta,fps);
interval = setInterval(function(){
//清空畫布
ctx.clearRect(0,0,canvas.getAttribute("width"),canvas.getAttribute("height"));
//更新數據
sprite.update(canvas);
//保存狀態
ctx.save();
//移動坐標
ctx.translate(sprite.dx,sprite.dy);
ctx.scale(scale,scale);
ctx.drawImage(img,sprite.sx,sprite.sy,sprite.sw,sprite.sh,0,0,sprite.dw,sprite.dh);
//恢復狀態
ctx.restore();
},1);
}
</script>
源碼下載:donghua3.rar