废话不多说,直接上代码,拿走即用
<!DOCTYPE html>
<html>
<head>
<title>Canvas Example</title>
</head>
<body>
<canvas id="canvas" width="1397" height="1080"></canvas>
<script>
var ctx = document.getElementById('canvas').getContext('2d');
var imgSrcs = [];
for (var i = 1; i <= 100; i++) {
imgSrcs.push(`你要添加进去的图片路径`);
}
// 正序显示图片
function showImages() {
var curIndex = 0;
var timer = setInterval(function() {
var img = new Image();
img.onload = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
curIndex++;
if (curIndex >= imgSrcs.length) {
clearInterval(timer);
setTimeout(reverseImages, 100); // 等待一秒切换为倒序播放
}
};
img.src = imgSrcs[curIndex];
}, 80);
}
// 倒序显示图片
function reverseImages() {
var curIndex = imgSrcs.length - 1;
var timer = setInterval(function() {
var img = new Image();
img.onload = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
curIndex--;
if (curIndex < 0) {
clearInterval(timer);
setTimeout(showImages, 100); // 等待一秒切换为正序播放
}
};
img.src = imgSrcs[curIndex];
}, 80);
}
showImages();
</script>
</body>
</html>
如果你使用的是vue,
<canvas ref="canvas" width="1920" height="1080" />
然后只需要将
document.getElementById('canvas').getContext('2d')
替换成
const canvas = ref<HTMLCanvasElement | null>(null)
剩下的都一样了