Choose folder and draw images on HTML5 Canvas

by Génesis García Morilla

HTML

<input type="file" webkitdirectory accept="image/*">
<canvas></canvas>

JavaScript

const canvas_ = document.querySelector('canvas')
canvas_.height = 0
const context_ = canvas_.getContext('2d')
let images_ = []

function loadCanvas(dataURL, num_images) {
  const image = new Image()

  image.onload = function() {
    canvas_.width = this.width > canvas_.width ? this.width : canvas_.width
    canvas_.height = canvas_.height + this.height

    images_.push(this)

    // Draw on canvas when all images are loaded
    if (images_.length == num_images) {
    	let y = 0
      images_.forEach((img, i, a) => {
      	y = i && (y + a[i - 1].height)
        context_.drawImage(img, 0, y)
      })
    }
  }

  image.src = dataURL
}

function readFiles(e) {
  const files = e.target.files
  if (!files.length) return;

  [...files].forEach(file => {
    if (file.type == 'image/jpeg')
      loadCanvas(URL.createObjectURL(file), files.length)
  });
}

document.querySelector('input').onchange = readFiles