簡體   English   中英

多個畫布不繪制圖像

[英]Multiple canvas are not drawing image

我想預覽用戶想要上傳的圖片。 我試圖為每個圖像創建一個畫布,以便更容易使用。

如果我選擇多個圖像,則最后一個圖像顯示所有圖像都要顯示。

<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);
    }
  }

將代碼提取到另一個函數,您可以獲取所有畫布。

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);
 };

這是JSFiddle!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM