0

有没有办法循环显示一组图像,依次显示每一张(一次只有一张,每张新的和前一张在同一个地方)?我将如何做到这一点?

我设法用 jQuery 创建了这种效果,其中我会淡入和淡出每个图像。有没有办法用 JavaScript 做到这一点,而不需要额外的库?

4

1 回答 1

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>
于 2013-04-30T01:54:12.360 回答