美文网首页程序员
canvas精灵图制作人物左右移动

canvas精灵图制作人物左右移动

作者: infi_ | 来源:发表于2018-06-30 18:28 被阅读0次

静态效果


动态效果

这里请注意SpriteSheetPainter的参数是一个数组 里面表示每个精灵图的坐标
代码如下

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)


}

相关文章

网友评论

    本文标题:canvas精灵图制作人物左右移动

    本文链接:https://www.haomeiwen.com/subject/iafxuftx.html