我在将图像放置在数组中并将其显示在画布对象中时遇到了一些麻烦。
Jscript代码段
canvas = document.getElementById('slideshow');
canvasContent = canvas.getContext('2d');
var elements = document.getElementsByClassName('slides');
for (var index = 0; index <= elements.length; index += 1)
{
arrFoto[index] = elements[index];
}
canvasContent.drawImage(arrFoto[huidigeIndex], 0, 0);
这是html文件的一部分
<div class="container">
<div class="slides">
<img src="data/images/slideshow/3.png" />
<img src="data/images/slideshow/4.jpg" />
<img src="data/images/slideshow/5.png" />
</div>
<canvas id="slideshow" width="700" height="300"></canvas>
</div>
我究竟做错了什么?
谢谢!
最佳答案
您必须遍历<img>
中的.slides
元素,如下所示
var canvas = document.getElementById('slideshow');
var canvasContent = canvas.getContext('2d');
var elements = document.getElementsByClassName('slides');
var arrFoto = Array();
for (var index = 0; index < elements.length; index++) {
var imgs = elements[index].getElementsByTagName('img');
for(var x = 0; x < imgs.length; x++)
arrFoto[arrFoto.length] = imgs[x];
}
for(var huidigeIndex=0; huidigeIndex < arrFoto.length; huidigeIndex++)
canvasContent.drawImage(arrFoto[huidigeIndex], 0, 0);
在您的代码中,您有
index <= elements
(注意<=
),它将使循环的最后一次迭代产生elements[index] is undefined
某种错误(JS数组以0索引开头)关于javascript - 将图像排列成阵列并显示,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16310077/