迭代显示一组图像,一次只显示1个

时间:2013-04-30 01:14:58

标签: javascript html css image

有没有办法循环显示一定数量的图像,依次显示每个图像(每次只显示1个,每个新图像与前一个图像位于同一个位置)?我该如何做到这一点?

我设法用jQuery创建这种效果,我将fadeIn和fadeOut每个图像。有没有办法用JavaScript做这个,没有额外的库?

1 个答案:

答案 0 :(得分:0)

我使用此代码来执行您所说的内容。

注意:它将在最后一张图像上停止。

<script type="text/javascript">
// <!--
var imagePaths = ["images/slide1.jpg", "images/slide2.jpg", "images/slide3.jpg"];
var showCanvas = null;
var showCanvasCtx = null;
var img = document.createElement("img");
var currentImage = 0;
var revealTimer;
var timeoutVariable = 3000;

window.onload = function () {
  showCanvas = document.getElementById('SlideShowCanvas');
  showCanvasCtx = showCanvas.getContext('2d');
  img.setAttribute('width', '560');
  img.setAttribute('height', '343');
  switchImage();
  setInterval(switchImage, timeoutVariable);
}

function switchImage() {
// Loop once
if (currentImage >= imagePaths.length) {
  clearInterval(revealTimer);
  clearTimeout(timeoutVariable);
} else {
  img.setAttribute('src', imagePaths[currentImage++]);
  showCanvasCtx.globalAlpha = 0.1;
  revealTimer = setInterval(revealImage, 100);
}

function revealImage() {
  showCanvasCtx.save();
  showCanvasCtx.drawImage(img, 0, 0, 560, 343);
  showCanvasCtx.globalAlpha += 0.1;
  if (showCanvasCtx.globalAlpha > 1.0)
  clearInterval(revealTimer);
  showCanvasCtx.restore();
}
// -->
</script>

哎呀

忘了添加html

<canvas id="SlideShowCanvas" style="width: 560px; height: 343px;" width="560px" height="343px">
  <div style="width: 560px; text-align: center; vertical-align: middle; height: 343px; border: 1px solid #C0C0C0;">
    <span style="width: 560px; height: 343px;">
      <br /><br />Your browser does not support<br />the html5 canvas object!<br /><br /><a href="http://www.microsoft.com/ie">Click Here To Download Microsoft's</a><br />Feature Rich Internet Explorer Web Browser<br />
    </span>
  </div>
</canvas>