0
我已經創建了單個圖像上傳,並把圖像畫布,這裏的demo。現在我想修改我的腳本多個上傳圖片,這我修改劇本:jquery多個圖像上傳並把圖像到畫布元素
JS:
$(function() {
$('#file-input').on('change',function(e) {
if (!e.target.files.length || !window.FileReader) {
return;
} else {
var countedfiles = $('#thumbnails canvas[data-other="fileCanvas"]').length; // check lenght of file canvas
for (var i = 0; i < e.target.files.length; i++) {
if (countedfiles > 0){
var numb = countedfiles + 1;
} else {
var numb = i;
}
var file = e.target.files[i], imageType = /image.*/;
if (!file.type.match(imageType))
return;
var reader = new FileReader();
reader.onload = fileOnload(numb);
reader.readAsDataURL(file);
}
}
});
function fileOnload(numb,e) {
var $img = $('<img>', { src: e.target.result }); // this line is error
var newCanvas = '<canvas class="canvas" width="120px" height="120px" data-other="fileCanvas" id="canvas-'+numb+'"></canvas>';
$('#thumbnails').append(newCanvas);
var canvas = $('#canvas-'+numb)[0];
var context = canvas.getContext('2d');
$img.load(function() {
var maxWidth = 120; // Max width for the image
var maxHeight = 120; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = this.width; // Current image width
var height = this.height; // Current image height
// Check if the current width is larger than the max
if(width > maxWidth){
ratio = maxWidth/width; // get ratio for scaling image
this.width = maxWidth; // Set new width
this.height = height * ratio; // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
}
var width = this.width; // Current image width
var height = this.height; // Current image height
// Check if current height is larger than max
if(height > maxHeight){
ratio = maxHeight/height; // get ratio for scaling image
this.height = maxHeight; // Set new height
this.width = width * ratio; // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
}
var newWidth = this.width;
var newHeight = this.height;
context.drawImage(this, 0, 0, newWidth, newHeight);
});
}
});
HTML
<input type="file" id="file-input" multiple>
<div id="thumbnails"> </div>
但我得到的控制檯此錯誤:
Uncaught TypeError: Cannot read property 'target' of undefined