Skip to content

Instantly share code, notes, and snippets.

@john92paul
Last active August 27, 2020 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save john92paul/a8d42e246d03d92a1fab73958b25c6a3 to your computer and use it in GitHub Desktop.
Save john92paul/a8d42e246d03d92a1fab73958b25c6a3 to your computer and use it in GitHub Desktop.
<!-- HTML -->
<html>
<body>
<div>
<input type="file" id="imageInput" accept = "image/*">
<canvas id= "myCanvas" width="1000" height="700"></canvas>
</div>
</body>
</html>
<!-- Javascript -->
<script>
let imgInput = document.getElementById('imageInput');
imgInput.addEventListener('change', function(e) {
if(e.target.files) {
let imageFile = e.target.files[0]; //here we get the image file
var reader = new FileReader();
reader.readAsDataURL(imageFile);
reader.onloadend = function (e) {
var myImage = new Image(); // Creates image object
myImage.src = e.target.result; // Assigns converted image to image object
myImage.onload = function(ev) {
var myCanvas = document.getElementById("myCanvas"); // Creates a canvas object
var myContext = myCanvas.getContext("2d"); // Creates a contect object
myCanvas.width = myImage.width; // Assigns image's width to canvas
myCanvas.height = myImage.height; // Assigns image's height to canvas
myContext.drawImage(myImage,0,0); // Draws the image on canvas
let imgData = myCanvas.toDataURL("image/jpeg",0.75); // Assigns image base64 string in jpeg format to a variable
}
}
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment