When a user uploads an image I want to resize the image with canvas. The code below works when you just upload one image. But if you select multiple images the canvas item doesnt display an image (only on the last canvas element) does anyone know what is going wrong please?
https://jsfiddle.net/4ycgqyau/
function prepPreview(input) {
var container = document.getElementById("preview");
var files = jQuery(input).get(0).files;
for (var i = 0; i < files.length; i++) {
// create canvas element & resize image
var canvasEl = document.createElement("canvas");
canvasEl.id = 'canvas_' + i;
canvasEl.width = "250";
canvasEl.height = "140";
container.appendChild(canvasEl);
var canvas = document.getElementById('canvas_' + i);
var context = canvas.getContext('2d');
var reader = new FileReader();
reader.onload = function(event) {
var imageObj = new Image();
imageObj.onload = function() {
var wrh = imageObj.width / imageObj.height;
var newWidth = canvas.width;
var newHeight = newWidth / wrh;
if (newHeight > canvas.height) {
newHeight = canvas.height;
newWidth = newHeight * wrh;
}
context.drawImage(imageObj, 0, 0, newWidth, newHeight);
};
imageObj.src = reader.result;
}
reader.readAsDataURL(files[i], 'canvas_' + i);
console.log(files[i], 'canvas_' + i);
// create input
var input = document.createElement("input");
input.type = "text";
input.setAttribute('maxLength', 150);
input.name = "caption[" + i + "]";
container.appendChild(input);
// create row around image/input
var row = document.createElement("div");
row.className = 'user-uploads__row';
canvasEl.parentNode.insertBefore(row, canvasEl, input);
row.appendChild(canvasEl);
row.appendChild(input);
}
}