Last active
September 4, 2022 14:11
-
-
Save NatalyaDol/9cd4e465c17432e4bc5667309b1d06f2 to your computer and use it in GitHub Desktop.
Image resize and download canvas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h2>Select an image</h2> | |
<input type="file" name='image' multiple id='fileInput' /> | |
<!-- Div rehnders local image from fileList --> | |
<div id='grid' style='border: 3px solid red; width: 300px; height: 300px; margin: 100px auto;'></div> | |
<h3>Canvas Resize</h3> | |
<!-- Canvas resizes local image and allows for download --> | |
<canvas id='imgResize'></canvas> | |
<a id="download" download="resized.png"><button type="button" onClick="Download()">Download Resized Image</button></a> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let img = new Image() | |
const canvas = document.getElementById('imgResize') | |
let ctx = canvas.getContext("2d"); | |
canvas.width = 150; | |
canvas.height = 150; | |
//Adds to div bg | |
const addLocalPlaceholder = (e) => { | |
let file = e.target.files | |
console.log(file) | |
let reader = new FileReader(); | |
reader.onload = (function(e){ | |
console.log('loaded') | |
document.getElementById('grid').style.backgroundImage = "url("+e.target.result+")"; | |
img.src = e.target.result | |
//img.src = reader.result; | |
}) | |
reader.readAsDataURL(file[0]) | |
img.onload = (function(){ | |
ctx.drawImage(img, 0, 0, 150, 150); | |
}) | |
//img = e.target.result; | |
} | |
document.getElementById('fileInput') | |
.addEventListener('change', addLocalPlaceholder, false) | |
//////////////////Download Logic | |
const Download = () => { | |
const download = document.getElementById("download"); | |
let image = document.getElementById("imgResize").toDataURL("image/png") | |
.replace("image/png", "image/octet-stream"); | |
download.setAttribute("href", image); | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#grid{ | |
background-size: cover; | |
background-position: center | |
} | |
#imgResize{ | |
border: solid green; | |
position: absolute; | |
left: 50%; | |
transform: translateX(-50%) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment