Skip to content

Instantly share code, notes, and snippets.

@NatalyaDol
Last active September 4, 2022 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NatalyaDol/9cd4e465c17432e4bc5667309b1d06f2 to your computer and use it in GitHub Desktop.
Save NatalyaDol/9cd4e465c17432e4bc5667309b1d06f2 to your computer and use it in GitHub Desktop.
Image resize and download canvas
<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>
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);
}
#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