[英]How do I load the image from file chooser and get it to load on the canvas so that i can edit it using Javascript?
我一直在使用一個稱為像素繪制的像素編輯器,我想創建一個按鈕,允許我將任何圖像加載到 canvas 上。 目前,我一直在網上研究和測試多種方法,但我仍然在努力加載圖像。這是script.js方法的代碼。
function showSelectedFile(){
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
var img = new Image();
var file = document.getElementById("inputfile");
var name = file.value.replaceAll("\\","").replace("C:fakepath","").replace(".png","");
document.getElementById("myText").value = name;
window.URL = window.URL || window.webkitURL;
img.onload = function()
{
context.drawImage(img,0,0)
}
img.src = "/Users/angadp/Dropbox/Mac/Downloads/pixel-paint-master/" + name + ".png";
}
此外,在 script.js 文件中,我嘗試使用 var canvas = document.getElementById("canvas-div") 但它收到以下錯誤“Uncaught TypeError: canvas.getContext is not a function”。
在index.html文件中,代碼當前正在使用<div id="canvas-div"></div>
。 所以我不太確定如何將圖像加載到使用 div 標簽的 canvas 上。 同樣在 html 文件的開頭,我正在使用<input id='inputfile' type='file' accept = ".png" name='inputfile' onChange='showSelectedFile()'>
這使得選擇文件按鈕。
我還有一張像素畫的圖片,這樣你就知道我在說什么了。
您能否為我提供一些有關如何解決所有這些解決方案的幫助。 謝謝你。 我還附上了原始像素繪畫的超鏈接,以便您下載和測試它。
您可以在文件change
時加載圖像。 然后createObjectURL
(即data:something;base64)。 然后將其加載到圖像上,最后將其繪制在<canvas>
上。
function loadFile(event) { var canvas = document.querySelector("canvas"); var ctx = canvas.getContext('2d'); var dummy = document.getElementById('dummy'); dummy.src = URL.createObjectURL(event.target.files[0]); dummy.onload = function() { ctx.drawImage(dummy, 0, 0, 600, 300); // Set line width ctx.lineWidth = 10; ctx.beginPath(); ctx.moveTo(50, 140); ctx.lineTo(150, 60); ctx.lineTo(250, 140); ctx.closePath(); ctx.stroke(); // free memory URL.revokeObjectURL(dummy.src) dummy.parentNode.removeChild(dummy) } };
canvas { width: 600px; height: 300px; }
<input type="file" accept="image/*" onchange="loadFile(event)"> <canvas></canvas> <img id="dummy" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.