Load an image into a canvas

Stack Overflow question - http://stackoverflow.com/questions/32840813/angular-file-upload

by vijayweb

HTML

<button>Load image into Canvas</button>
<br />
<br />
<canvas></canvas>

CSS

canvas {
            background-color: blue;
        }

JavaScript

var canvas = document.getElementsByTagName('canvas')[0];
canvas.width  = 800;
canvas.height = 600;




// source of a large image - replace this with the URL of the uploaded image (served from the database)
var IMAGE_SRC = "http://cdn-media-1.lifehack.org/wp-content/files/2014/09/activities-on-the-beach.jpg";

// set the height for the thumbnail - your uploader currently has 100
var height = 100;

function drawImage() {
    // create a new Image object
    var img = new Image();

    // set up the onLoad handler on the image object to draw the thumbnail into the canvas
    img.onload = function () {
        // calculate the thumbnail width for the fixed height above, respecting the image aspect ratio
        var width = this.width / this.height * height;
        
        // set the dimensions on the canvas
        $("canvas").attr({
            width: width,
            height: height
        });
        
        // draw the image from the loaded image object
        $("canvas")[0].getContext("2d").drawImage(img, 0, 0, width, height);
    };

    // set the source of the image object to the URL of the uploaded image (served from the database)
    img.src = IMAGE_SRC;
}

// Do all of this when the button is clicked
$("button").click(drawImage);