[英]Javascript upload image onto canvas
我想上傳圖像文件並在 canvas 上顯示。 所以我寫了如下代碼
HTML 代碼在這里
<div class="img_upload">
<input type="file" id="real-input" class="input-btn" accept="img/*" required multiple>
<button class="browse-btn">Image Upload</botton>
</div>
<canvas id="jsCanvas" class="canvas" width="600" height="400"></canvas>
javascript 代碼在這里
const canvas = document.querySelector('#jsCanvas');
const ctx = canvas.getContext('2d');
const browseBtn = document.querySelector('.browse-btn');
const realInput = document.querySelector('#real-input');
function readInputFile(e) {
var file = e.target.files;
const img = new Image();
var reader = new FileReader();
reader.onload = function (e) {
img.src = e.target.result;
};
reader.readAsDataURL(file[0]);
ctx.drawImage(img, 0, 0);
}
// button act like input tag
browseBtn.addEventListener('click', () => {
realInput.click();
});
realInput.addEventListener('change', readInputFile);
但是ctx.drawImage(img, 0, 0);
不起作用。
我檢查了值console.log(img)
的 img ,然后它的值是<img src="incoding very long base 64 data">
寫完body.appendChild(img);
后我可以看到圖像了 .
如何在 canvas 上激活 drawImage? 這里有什么問題?
你好我改變你的代碼試試這個:
const canvas = document.querySelector('#jsCanvas'); const ctx = canvas.getContext('2d'); const realInput = document.querySelector('#real-input'); realInput.addEventListener('change', handleImage, false); function handleImage(e){ var reader = new FileReader(); reader.onload = function(event){ var img = new Image(); img.onload = function(){ canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img,0,0); } img.src = event.target.result; } reader.readAsDataURL(e.target.files[0]); }
<div class="img_upload"> <input type="file" id="real-input" class="input-btn" accept="img/*" required multiple> </div> <canvas id="jsCanvas" class="canvas" width="600" height="400"></canvas>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.