靜態(tài)效果
動態(tài)效果
這里請注意SpriteSheetPainter的參數(shù)是一個數(shù)組 里面表示每個精靈圖的坐標
代碼如下
var velocityX=10 //X軸的位移速度
var left1=100 //X軸的起始位置 這個值控制人物的橫坐標
var img_start=imgid //最開始的精靈貼圖
var advance_or="left" //最開始向左移動
SpriteSheetPainter=function(cells){
this.cells=cells||[]
this.cellIndex=0
}
SpriteSheetPainter.prototype={
advance:function(){
if(this.cellIndex==(this.cells.length-1)){this.cellIndex=0}else{
this.cellIndex++
}
},
advance2:function(){
if(this.cellIndex==0){this.cellIndex=(this.cells.length-1)}else{
this.cellIndex--
}
},
paint:function(context,canvas){
var cell=this.cells[this.cellIndex]
left1=canvas.left-velocityX
if(left1<0){ //人物左移臨界點判斷
advance_or="right"
velocityX=-velocityX
img_start=imgid2
context.drawImage(img_start,cell.x,cell.y,cell.w,cell.h,canvas.left,canvas.top,canvas.w,canvas.h)
}
if(left1+canvas.w>1024){ //人物右移臨界點判斷
advance_or="left"
velocityX=-velocityX
img_start=imgid
context.drawImage(img_start,cell.x,cell.y,cell.w,cell.h,canvas.left,canvas.top,canvas.w,canvas.h)
}
else{
if(advance_or=="left"){
img_start=imgid
this.advance()
}
if(advance_or=="right"){
img_start=imgid2
this.advance2()
}
context.drawImage(img_start,cell.x,cell.y,cell.w,cell.h,canvas.left,canvas.top,canvas.w,canvas.h)
}
}
}
window.onload=function(){
//bomb.paint(context)
var some=new SpriteSheetPainter([{x:0,y:0,w:41,h:64},
{x:53,y:0,w:41,h:64},
{x:106,y:0,w:41,h:64},
{x:159,y:0,w:41,h:64},
{x:212,y:0,w:41,h:64},
{x:265,y:0,w:41,h:64},
{x:318,y:0,w:41,h:64},
{x:371,y:0,w:41,h:64},
{x:424,y:0,w:41,h:64}
])
some.paint(context,{left:100,top:100,w:53,h:64})
var now=0
var last=0
function animate(){
now=(+new Date)
var hi=now-last
if(parseInt(hi)>100){
last=now
context.clearRect(0,0,canvas.width,canvas.height)
// some.advance()
some.paint(context,{left:left1,top:100,w:53,h:64})
}
requestAnimationFrame(animate)
}
requestAnimationFrame(animate)
}