多个画布不绘制图像

时间:2015-10-21 15:52:52

标签: javascript jquery html5

我想预览用户想要上传的图片。我试图为每个图像创建一个画布,以便更容易使用。

如果我选择多张图片,则最后一张图片会显示所有图片。

<input type="file" id="browseImages" multiple="multiple" accept="image/*">
<output id="list"></output>

document.getElementById('browseImages').addEventListener('change', handleFileSelect, true);

  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {
      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

    var canvas = document.createElement('canvas');
    canvas.width  = 110;
    canvas.height = 100;
    var ctx = canvas.getContext("2d");
    var img = new Image;
    img.onload = function() {
    ctx.drawImage(img, 0, 0, 100, 100);
}
    img.src = window.URL.createObjectURL(f);
    document.getElementById('list').appendChild(canvas);
    window.URL.revokeObjectURL(f);
    }
  }

1 个答案:

答案 0 :(得分:1)

将代码提取到另一个函数,您可以获得所有画布。

Html代码:

<input type="file" id="browseImages" multiple="multiple" accept="image/*">
<output id="list"></output>

Javascript代码:

document.getElementById('browseImages').addEventListener('change', handleFileSelect, true);

function handleFileSelect(evt) {                
  var files = evt.target.files; // FileList object

  // Loop through the FileList and render image files as thumbnails.
  for (var i = 0; i < files.length; i++) {
    var f = files[i];
    // Only process image files.
    if (!f.type.match('image.*')) {
      continue;
    }
    createCanvas(f);
  }
}

function createCanvas(f){
  var canvas = document.createElement('canvas');
  canvas.width  = 110;
  canvas.height = 100;
  var ctx = canvas.getContext("2d");
  var img = new Image();
  img.src = window.URL.createObjectURL(f);
  window.URL.revokeObjectURL(f);

  img.onload = function() {
    ctx.drawImage(img, 0, 0, 100, 100);
  }

  document.getElementById('list').appendChild(canvas);
 };

Here is the JSFiddle!