0

我不明白为什么下面的代码有时会显示我选择的所有项目,大多数时候会显示一些,而且大部分是在第 3 次尝试中,根本没有显示任何内容。

因为它在多次尝试中做了不同的事情,所以我无法查明错误的原因。

例如,您加载 3 张图片,它不显示它们(从检查元素我可以看到它们),然后您加载 7 张图片,其中包含 3 张以前的图片,它只显示 3..

我用铬。看起来很简单的代码。这是完整的代码(您必须将图片放在同一文件夹中):

<!DOCTYPE>
<html>
<head>
<style>
canvas{border: #090 1px solid;}

</style>
<script type="application/javascript" language='javascript'>
window.onload = draw;
window.onload = getFiles;
var namelist = [];
function draw(){
    // if it has canvas i remove and replace it, i just found 
    //.replaceChild so i'll be using it next time
    var dbody = document.getElementById('dbody');

    if (dbody.childNodes.length === 1){
        console.log(dbody.firstChild)
        can=document.getElementById('canvas')
        dbody.removeChild(can);
    }
    // Creating canvas
    var canvas = document.createElement("canvas");
    canvas.id='canvas'
    canvas.setAttribute('width',700)

    // create html5 context object to enable draw methods
    var ctx = canvas.getContext('2d');
    dbody.appendChild(canvas);
    var x = 10; // picture start cordinate
    var y = 10; // -------||---------
    var buffer = 10; // space between pictures
    // Insert images to canvas
    for (i=0; i<namelist.length; i++){
        var image = new Image();
        image.src = namelist[i];
        canvas.appendChild(image);
        ctx.drawImage(image,x,y,50,50)
        x+=50+buffer;
    }
}
function getFiles(){

    var picturesFiles = document.getElementById('pictures')
    picturesFiles.addEventListener('change', function(event){
        namelist.length = 0;// empty name list
        var files = picturesFiles.files;
        for (i=0; i< files.length; i++){
            namelist.push(files[i].name);
        }
        draw();
    }, true);

}

</script>
</head>
<body>
<div id='dbody'></div>
<div>
    <input type="file" id='pictures' multiple="">
</div>
</body>
</html>
4

1 回答 1

1

你需要做一些事情:http: //jsfiddle.net/NMtfc/2/

for (i = 0; i < namelist.length; i++) {
    var image = new Image();

    canvas.appendChild(image);
    (function(img) {                         // this closure will allow us to maintain our reference to the image object correctly
        img.onload = function() {            // wait til the image loads
            ctx.drawImage(img, x, y, 50, 50)
            x += 50 + buffer;                // increment x here so it isn't the same for each element. 
        }
    })(image);
    image.src = namelist[i];
}

我刚刚意识到它也可以简单地写成:

for (i = 0; i < namelist.length; i++) {
    var image = new Image();
    image.onload = function() {
        ctx.drawImage(this, x, y, 50, 50)  // 'this' will refer to the image.
        x += 50 + buffer;
    };
    image.src = namelist[i];
}
于 2012-12-07T18:14:22.897 回答