如何正确显示从数组获取的图像

时间:2018-07-08 18:05:15

标签: javascript arrays image

我正在尝试从页面加载的结果中将数组中的随机图像显示在屏幕上。我知道页面成功获取了随机的img src,但是物理图像从未出现。我需要在html中引用它吗?我将如何获取该随机图像src以制作可见图像。

<!DOCTYPE html>
<html>
    <head>
        <title>Hiragana Flash Cards</title>
    </head>
    <body>
        <h2>Hiragana Flash Cards</h2>
        <script>
            var imgArray = new Array();
            imgArray[0] = new Image();
            imgArray[0].src = 'a.png';
            imgArray[1] = new Image();
            imgArray[1].src = 'i.png';
            imgArray[2] = new Image();
            imgArray[2].src = 'u.png';
            imgArray[3] = new Image();
            imgArray[3].src = 'e.png';
            imgArray[4] = new Image();
            imgArray[4].src = 'o.png';
            imgArray[5] = new Image();
            imgArray[5].src = 'ka.png';

            function imgRandom(imgArr) {
                return imgArr[Math.floor(Math.random() * imgArr.length)];
                }
            console.log(imgRandom(imgArray)); 
        </script>
    </body>
</html>      

3 个答案:

答案 0 :(得分:0)

您需要图像添加到文档:

 var imgArray = new Array();
            imgArray[0] = new Image();
            imgArray[0].src = 'a.png';
            imgArray[1] = new Image();
            imgArray[1].src = 'i.png';
            imgArray[2] = new Image();
            imgArray[2].src = 'u.png';
            imgArray[3] = new Image();
            imgArray[3].src = 'e.png';
            imgArray[4] = new Image();
            imgArray[4].src = 'o.png';
            imgArray[5] = new Image();
            imgArray[5].src = 'ka.png';

            function imgRandom(imgArr) {
                return imgArr[Math.floor(Math.random() * imgArr.length)];
                }
            var randomImage = imgRandom(imgArray); //Create the image
            document.getElementById('container').appendChild(randomImage); // Append the image
            
<!DOCTYPE html>
<html>
    <head>
        <title>Hiragana Flash Cards</title>
    </head>
    <body>
        <h2>Hiragana Flash Cards</h2>
        <!--You can place the image here -->
        <div id="container"></div>
    </body>
</html>  

查看appendChild()文档

答案 1 :(得分:0)

像这样将它附加到身体上

document.body.append(imgRandom(imgArray));

答案 2 :(得分:0)

您可以修改 img 标记的 src 变量并将其设置为图像URL。

摘要

var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'blue.png';
imgArray[1] = new Image();
imgArray[1].src = 'green.png';

function imgRandom(imgArr) {
  return imgArr[Math.floor(Math.random() * imgArr.length)];
}

document.getElementById("random").src = imgRandom(imgArray).src;
console.log(imgRandom(imgArray));
<!DOCTYPE html>
<html>
    <head>
        <title>Hiragana Flash Cards</title>
    </head>
    <body>
        <h2>Hiragana Flash Cards</h2>
        <img id="random">
    </body>
</html>

简短版

document.getElementById("random").src = imgRandom(imgArray).src;