JSFiddle - React, Tailwind, and code Playground
by Admiral Potato
HTML
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<form id="form" encType="multipart/form-data">
<input id="file" type="file" />
<input type="submit" />
</form>
<script src="image_upload_shrink.js"></script>
CSS
html, body {
margin: 0;
font-size: 16px;
font-family: sans-serif;
}
.yup, form {
position: relative;
display: block;
border: 1px solid black;
padding: 2em;
}
input {
display: block;
width: 30%;
padding: 0.5em 15px;
margin: 1em auto;
}
img, canvas {
display: block;
margin: 1em auto;
max-width: 1024px;
border: 1px solid black;
}
a{
position: absolute;
top: 0;
right: 0;
display: block;
width: 2em;
height: 2em;
background-color: #f00;
}
JavaScript
var formElement = document.getElementById('form'),
fileElement = document.getElementById('file'),
//src: https://stackoverflow.com/questions/3971841/how-to-resize-images-proportionally-keeping-the-aspect-ratio/14731922#14731922
calculateAspectRatioFit = function(srcWidth, srcHeight, maxWidth, maxHeight) {
var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
return { width: srcWidth*ratio, height: srcHeight*ratio };
},
imageShrinker = function(originalImageData){
var holder = document.createElement('div'),
closeBox = document.createElement('a'),
originalImage = document.createElement('img'),
generatedImage = document.createElement('img'),
imageScaleCanvas = document.createElement('canvas'),
context = imageScaleCanvas.getContext('2d');
//ref: https://html.spec.whatwg.org/multipage/scripting.html#dom-context-2d-imagesmoothingenabled
context.webkitImageSmoothingEnabled = true;
context.mozImageSmoothingEnabled = true;
context.imageSmoothingEnabled = true;
//ref: https://html.spec.whatwg.org/multipage/scripting.html#dom-context-2d-imagesmoothingquality
context.webkitImageSmoothingQuality = 'high';
context.mozImageSmoothingQuality = 'high';
context.imageSmoothingQuality = 'high';
holder.className = 'yup';
document.body.appendChild(holder);
holder.appendChild(closeBox);
holder.appendChild(originalImage);
holder.appendChild(imageScaleCanvas);
holder.appendChild(generatedImage);
closeBox.addEventListener('click', function(){
document.body.removeChild(holder);
});
originalImage.onload = function() {
var proportionalImageSize = calculateAspectRatioFit(
originalImage.width,
originalImage.height,
256,
256
);
imageScaleCanvas.width = proportionalImageSize.width;
imageScaleCanvas.height = proportionalImageSize.height;
context.drawImage(originalImage, 0, 0, imageScaleCanvas.width, imageScaleCanvas.height);
generatedImage.src =...