Upload file to Canvas

by Jon-Carlos Rivera

HTML

<canvas id="canvas" width="470" height="330"></canvas>
<input type="file" id="file-input">

JavaScript

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();
        // ...
        
    });
}