我不明白为什么下面的代码有时会显示我选择的所有项目,大多数时候会显示一些,而且大部分是在第 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>