canvas 绘制动画

function animation(opts){
      var canvas = document.createElement('canvas');
      canvas.id = 'cg-canvas'+Math.random();
      opts.container.appendChild(canvas);
      var realImgs = opts.imgs;
      canvas.width = opts.width||realImgs[0].width;
      canvas.height = opts.height||realImgs[0].height;
      var ctx = canvas.getContext('2d');
      
      var lastStamp = 0, currImg = 0;
      var step = function(stamp){
          if(stamp - lastStamp > 83){
              lastStamp = stamp;
              ctx.clearRect(0,0,canvas.width,canvas.height);
              try{
                  ctx.drawImage(realImgs[currImg],0,0);    
              }
              catch(e){
                  console.log(e);
              }
              currImg++;
          }
          if(currImg >= realImgs.length){
              currImg = 0;
          }
          window.requestAnimationFrame(step);    
      };
      step(120);
      return canvas;
    }

获取图片

function imgList(){
        var el=[];
        for(var i=0;i<26;i++){
          if(i<10){
              i='0'+i;
          }
          el.push('img/star/0' + i + '.jpg');
        }  
        return el; 
    }

图片换成对象

var imgList = imgList().map(function(ele){
      var img = new Image();
      img.src = ele;
      return img;
    }); 

参数获取

var opts={
      container: canvasTop,
      imgs: imgList,
      width: 640,
      height: 800
    }

你可能感兴趣的:(canvas 绘制动画)