建立 HTML
首先在 HTML 建立一個 File Upload 與一個 canvas
1 2
| <input type="file" /> <canvas id="canvas" width="800" height="600"></canvas>
|
綁定事件
接下來為 File Upload 綁定事件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| document.querySelector('input').addEventListener('change', function () { const file= this.files[0];
const canvas = document.getElementById('canvas'); let img = new Image;
img.onload = function () { canvas.getContext('2d').drawImage(img,0,0,800,600);
URL.revokeObjectURL(img.src); canvas.toBlob((blob) => { var reader = new FileReader();
reader.onloadend = function () { console.log(reader.result.split(",")[1]); } reader.readAsDataURL(blob); }, "image/jpeg", 0.8); }; img.src = URL.createObjectURL(file); }, false);
|