Canvas Image Animation (Crossfade)

走远了吗. 提交于 2019-12-02 09:50:54

I would use three canvases for this :

var imgs = [];

var rand = Math.random;
var common = "http://lorempixel.com/500/300?";
var imageURLs = [common + rand(), common + rand(), common + rand(), common + rand(), common + rand()];

var imagesOK = 0;
function loadAllImages(callback) {
  for (var i = 0; i < imageURLs.length; i++) {
    var img = new Image();
    imgs.push(img);
    img.onload = function() {
      imagesOK++;
      if (imagesOK >= imageURLs.length) {
        callback();
      }
    };
    img.src = imageURLs[i];
  }
}
var ctx = main.getContext('2d');
var last = main.cloneNode(true).getContext('2d');
var next = main.cloneNode(true).getContext('2d');

var current = 0;
var op = 1;

function nextImage() {
  if (current++ >= imgs.length - 1) current = 0;
  op = 1;
  fade();
}

function fade() {
  op -= .01;
  
  last.clearRect(0, 0, main.width, main.height);
  last.globalAlpha = op;
  last.drawImage(imgs[current], 0, 0);

  next.clearRect(0, 0, main.width, main.height);
  next.globalAlpha = 1 - op;
  next.drawImage(imgs[(current + 1) % (imgs.length)], 0, 0);

  ctx.clearRect(0, 0, main.width, main.height);
  ctx.drawImage(last.canvas, 0, 0);
  ctx.drawImage(next.canvas, 0, 0);

  if (op <= 0) setTimeout(nextImage, 1500);
  else requestAnimationFrame(fade);
}
loadAllImages(fade);
<canvas id="main" width="500" height="300"></canvas>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!