var fileInput = document.getElementById('file-input');
fileInput.addEventListener('change', function(e) {
var file = e.target.files[0],
imageType = /image.*/;
if (!file.type.match(imageType))
return;
var reader = new FileReader();
reader.onload = fileOnload;
reader.readAsDataURL(file);
});
function fileOnload(e) {
var img = document.createElement('img');
img.src = e.target.result;
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var maxWidth = parseFloat(canvas.width);
var maxHeight = parseFloat(canvas.height);
img.addEventListener('load', function() {
var widthRatio = maxWidth / this.width;
var heightRatio = maxHeight / this.height;
var scale = Math.max(widthRatio, heightRatio);
var newWidth = Math.floor(this.width * scale);
var newHeight = Math.floor(this.height * scale);
var overflowX = Math.floor((maxWidth - newWidth) / 2);
var overflowY = Math.floor((maxHeight - newHeight) / 2);
// Draw the scaled image
context.drawImage(this, overflowX, overflowY, newWidth, newHeight);
// At this point you want to do:
var data = canvas.toDataURL('image/jpeg', 1); // 0.8 = 80% quality
// Then send the data to server using XHR
// var xhr = new XMLHttpRequest();
// ...
});
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.