Canvas元素在第3次运行时出现奇怪的反应

时间:2012-12-07 17:44:08

标签: javascript html5-canvas

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

因为它在多次尝试时做了不同的事情,我无法确定错误的原因。

例如你加载3张图片,它没有显示它们(来自inspect元素我可以看到它们),然后你加载7张图片,其中包含3张图片,它只显示了3 ..

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

<!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>

1 个答案:

答案 0 :(得分: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];
}