Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

图片帧动画 #62

Open
xiaotiandada opened this issue Jan 19, 2021 · 0 comments
Open

图片帧动画 #62

xiaotiandada opened this issue Jan 19, 2021 · 0 comments

Comments

@xiaotiandada
Copy link
Owner

2020-11-16 23:16:37

切换img图片完成帧动画效果

<iframe src="https://codesandbox.io/embed/tupianzhengdonghua-kb2hh?fontsize=14&hidenavigation=1&theme=dark&view=preview" style="width:100%; height:200px; border:0; border-radius: 4px; overflow:hidden;" title="图片帧动画" allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" ></iframe>
// 加载所有图片资源
await Promise.all(
  this.layerConfig.map(async (v) => {
    console.log("v", v);
    return Promise.all(
      v.images.map(async (i, index) => {
        const img = document.createElement("img");
        img.src = i.src;
        await new Promise((resolve) => (img.onload = resolve));
        v.images[index].img = img;
      })
    );
  })

利用Promise先加载完所有图片

// 初始化图层
const layers = layerConfig.map((v) => {
  const layer = document.createElement("div");
  layer.classList.add("layer");
  container.appendChild(layer);
  return layer;
});

// 切换下一帧的方法
const changeToNextFrame = (layer, images, i) => {
  setTimeout(() => {
    const next = i === images.length - 1 ? 0 : i + 1;
    layer.removeChild(layer.firstChild);
    layer.appendChild(images[next].img);
    changeToNextFrame(layer, images, next);
  }, images[i].duration);
};

// 初始化图层内图片和帧动画
layerConfig.map((v, i) => {
  const a = v.images[0].img;
  layers[i].appendChild(a);
  if (v.images.length > 1 && v.loopTime > 0) {
    changeToNextFrame(layers[i], v.images, 0);
  }
});
  1. 生成图层添加到页面
  2. 添加图层图片和动画
  3. 用SetTimeout切换图片
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant