如何使用 JS 渲染预加载的图像

How to render preloaded images using JS

我被这个问题困住了,我花了 2 周的时间努力解决这个问题。

我已经能够在 HTML 页面加载时预加载图像,但我无法访问图像并且出现以下错误:

http://localhost/taskB/html/html/members/[object%20HTMLImageElement] 404 (Not Found) [object%20HTMLImageElement]:1 GET

我的代码如下,预加载函数被标记为正确但我无法弄清楚如何访问图像数组:

function preloaded() {
    var itemDesc = setDesc();
    var preload = new Array();
    var loadedimages = new Array();
    var countPreload = 0;
    for (var r = 1; r <= 4; r++) {
        for (var c = 1; c <= 5; c++) {
            preload[countPreload] = "../../images/slices/" + itemDesc + "/" + itemDesc + "_r" + r + "_c" + c + ".jpg";
            countPreload++;
        }
    }
    for (var i = 0; i<preload.length; i++){
        loadedimages[i] = new Image();
        loadedimages[i].src = preload[i];
    }
}

function buildImageHTML() {
    var itemDesc = setDesc(getUrlVars()["description"]);
    var countFile = 0
    var file = new Array();
    // START REDO the images for access
    var preload = new Array();
    var loadedimages = new Array();
    var countPreload = 0;    
    for (var r = 1; r <= 4; r++) {
        for (var c = 1; c <= 5; c++) {
            preload[countPreload] = "../../images/slices/" + itemDesc + "/" + itemDesc + "_r" + r + "_c" + c + ".jpg";
            countPreload++;
        }
    }
    for (var i = 0; i<preload.length; i++) {
        loadedimages[i] = new Image();
        loadedimages[i].src = preload[i];
    }
    //END REDO the images for access
    var writeThis = "";
    writeThis += "<table>";

    //Build Rows then columns
    for (var x = 1; x <= 4; x++) {
        writeThis += "<tr>";
        //Loop through and add five <td> cells to hold the image slices
        for (var y = 1; y <= 5; y++) {
            file = loadedimages[countFile];
            writeThis += "<td><img src=\"" + file + "\"></td>";
            countFile++;
        }
        writeThis += "</tr>";
    }
    writeThis += "</table>";
    var divImageObj = document.getElementById('divImageObject');
    divImageObj.style.display = 'block';
    divImageObj.innerHTML = writeThis;
}

我还有一个函数叫做 start():

function start() {
    preloaded();
}

我通过 onload 事件调用 start 函数,如下所示:

<body onload="start();">

一个要求是我必须使用innerHtml来渲染图像。

这里的任何指示都会很棒。

loadedimages 是 Image Objects 的数组。请改用 loadedimages[countFile].scr。

file = loadedimages[countFile].src;

最好从 HTML head 部分调用 preloaded() 。 onload 事件会在渲染所有页面后触发。

<html>
<head>
...
<script>
preloaded();
</script>
</head>
<body>
...