<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
canvas{
display:none;
}
</style>
</head>
<body>
<input id="file" type="file" multiple>
<div id="a"></div>
<script src="js/jquery.js"></script>
<script>
var fileInput = document.getElementById('file');
var fileLists = [];
var files;
var room_id;
var cover = 0;
var checked;
$('#file').on('change', function(event) {
files = fileInput.files; //重新取得[input type='file']資料
show_img();
});
function show_img(){
if(fileLists.length == 0){
checked = 1;
}
files = Array.prototype.slice.call(files); //將偽數組轉成陣列
fileLists = fileLists.concat(files); //concat() 方法用於連接兩個或多個數組(陣列)
//顯示圖片資訊
if (files.length !== 0) {
for (let i = 0; i < files.length; i++) {
let reader = new FileReader(); //FileReader 為預設物件,用來讀取檔案
let img = new Image();
reader.onload = (function() {
return function(e){
img.src = e.target.result;
img.onload = function(){
var canvas = document.createElement('canvas'); //創建canvas
var context = canvas.getContext('2d'); //2D圖像
// 图片原始尺寸
//console.log(img.src);
var originWidth = this.width;
var originHeight = this.height;
// 最大尺寸限制
var maxWidth = 100, maxHeight = maxWidth*originHeight/originWidth;
// 目标尺寸
var targetWidth = originWidth, targetHeight = originHeight;
canvas.width = maxWidth;
canvas.height = maxHeight;
// 清除画布
// 图片压缩
context.drawImage(img, 0, 0, maxWidth, maxHeight);
let base64 = canvas.toDataURL('image/jpeg',1.0);
$('#a').append(canvas);
console.log(base64);
let input_img = "<img src="+base64+">";
$('#a').append(input_img);
}
}
})();
reader.readAsDataURL(files[i]); //讀取檔案後執行load事件
}
}
event.target.value = ""; //讓剛被刪除的圖片可重複上傳
}
</script>
</body>
</html>
我依網路上的code 改成先canvas後再顯示圖片,現在迴圈只能顯示選取的最後一張,請問應該要怎麼改動呢?謝謝