vue+canvas模拟人物在地图上移动动画效果

使用vue+canvas实现人物图标在背景图中移动效果
1 引入canvas


2. 获取canvas对象,这个我是写在mounted周期中的

mounted () {
 let myCanvas = this.$refs.canvasPerson ;  
 this.ctx = myCanvas.getContext('2d');
 this.updatePage(this.ctx);
 }
 

3 实现函数

 updatePage(ctx){
	 var _this = this;
        var list = [];
        var personPicBlue = new Image();
        personPicBlue.src = "/public/images/battle/zb_2.png";
        list.push(personPicBlue);
        var airport = new Image();
        airport.src  = "/public/images/battle/airPlane.png";
        list.push(airport);

        //实现图片预加载
        var loadedImages = 0;    
        var numImages = list.length; 
        list.forEach(img =>{
            img.onload = function(){ 
              //当所有图片加载完成时,执行回调函数callback
              if (++loadedImages >= numImages) {  
                //设置定时器实现坐标的变化
                if(this.densityTimer){
                  clearInterval(this.densityTimer);
                }else{
                  this.densityTimer = setInterval(function(){
                   ctx.clearRect(0,0,1060,700)
                    _this.x = _this.x+1;
                    _this.y= _this.y+1;
                    _this.fillCanvas(ctx,0,0,1060,700);
                    var canvasWidth = 1060;
                    _this.drawGlass(ctx,airport,0,0,1060,700);
                    _this.drawPerson(ctx,personPicBlue,300,400,"lishi");   
                  },250*1)
                }
              }  
            }
        })   
      },
      drawGlass(ctx,glassPic,poxS,poyS,width,height){//绘制背景
        ctx.drawImage(glassPic,poxS,poyS,width,height);
      },

      drawPerson(ctx,personPic,posX,posY,name){//绘制人物图标
        var _this = this;
        ctx.drawImage(personPic,parseFloat(posX)+_this.x,parseFloat(posY)+_this.y,20, 27);
        ctx.font="11px Arial";
        ctx.fillStyle = "black"
        ctx.fillText(name,parseFloat(posX)+_this.x+25,parseFloat(posY)+_this.y+15);
      },

4 完整代码





你可能感兴趣的:(vue+canvas模拟人物在地图上移动动画效果)