1
我正在學習HTML5和Javascript,我試圖在畫布上繪製圖像。如果我在打破下面標記的行之後遍歷代碼,我有以下代碼可以繪製圖像。如果我不調試,那麼圖像根本就沒有繪製。我究竟做錯了什麼?火狐10與FireBug 1.9。爲什麼在調試時在畫布上繪製圖像,但在運行時不能繪製圖像?
請注意,雖然有一個循環來處理多個圖像,但我只選擇了一個。我認爲如果一個人不工作,一個人也不會工作。 ;-)
<!DOCTYPE html>
<html>
<body>
<input type="file" id="files" name="files[]" multiple />
<canvas id="picCanvas" />
<script>
function handleFileSelect(evt) {
var files = evt.target.files;
// Loop through the FileList and render images
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
return function (e) {
var img = document.createElement('img'); // <-- BREAK HERE!
img.src = e.target.result;
var canvas = document.getElementById('picCanvas');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>
非常感謝三角洲!有趣的是,答案現在如此明顯。 :-) – KatoMan 2012-02-13 12:31:58