JS帧动画

const drawImage = (requireModule, file, cb, customW, customH) => {
  let count = 0;
  let ctx = null;
  let timeout = null;
  const imgSrcs = [];
  const images = [];
  const delay = 100;
  const canvas = document.getElementById('canvas');
  for (var j = 0; j < requireModule.keys().length; j++) {
    imgSrcs.push(`${file}` + requireModule.keys()[j].substr(2, requireModule.keys()[j].length));
  }
  const animation = (i) => {
    ctx = canvas.getContext('2d');
    if (!ctx) return
    const w = customW || Math.floor(images[0].width / 2);
    const h = customH || Math.floor(images[0].height / 2);
    canvas.width = w;
    canvas.height = h;
    ctx.clearRect(0, 0, w, h);
    ctx.drawImage(images[i], 0, 0, w, h);
    if (i === imgSrcs.length - 1) {
      timeout = setTimeout(() => {
        animation(0);
      }, delay);
    } else {
      timeout = setTimeout(() => {
        animation(i + 1);
      }, delay);
    }
  }
  for (let i = 0; i < imgSrcs.length; i += 1) {
    images[i] = new Image();
    images[i].src = require(`${imgSrcs[i]}`).default;
    images[i].onload = () => {
      count += 1;
      if (count === imgSrcs.length) {
        animation(0);
        if(cb) {
          cb(Math.floor(images[0].height / 2));
        }
      }
    }
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值