I have been using a pixel editor called pixel paint and I wanted to create a button that allows me to load any image onto the canvas. Currently, I have been researching and testing multiple methods online and I am still struggling to get the image loaded in. Here is the code for the script.js method.
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";
}
Also, in the script.js file I have tried to use var canvas = document.getElementById("canvas-div") but it gets the following error "Uncaught TypeError: canvas.getContext is not a function".
In the index.html file the code is currently using <div id="canvas-div"></div>
. So I am not really sure how to load the image onto the canvas that is using the div tag. Also at the beginning of the html file I am using <input id='inputfile' type='file' accept = ".png" name='inputfile' onChange='showSelectedFile()'>
which makes the choose file button.
I also have a picture of pixel paint so that you would know what I am talking about.
Can you please provide me with some help on how to solve all these solutions. Thank you. I have also attached the hyperlink to the original pixel-paint so that you can download and test it.
You can load image on change
of file. Then createObjectURL
(that's data:something;base64). Then load it on an image finally draw it on the <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" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.