Tuesday, August 4, 2015

Loading Images For HTML5 Canvas

First, make sure you've declared the canvas and its 2d context:

//the canvas element var canvas = document.getElementById("canvas"); //the set of canvas tools your working with var ctx = canvas.getContext("2d");

Then we have to load the image with a new image object and give the object a callback to execute once the image is loaded:

var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); //new image object var img = new Image(); //give it the path to the image you're loading img.src = "/img/obama.png"; //callback to execute once image is loaded //side-note: you can name anonymous functions img.onload = function handleLoad() { }

Once your image is loaded you can draw it onto your canvas inside your callback:

var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var img = new Image(); img.src = "/img/obama.png"; img.onload = function handleLoad() { //draw the image onto the canvas //in this example the drawImage takes in four parameters: //x - x coordinate on the canvas to render image //y - y coordinate on the canvas to render image // width - the width to draw the whole image // height - the height to draw the whole image //img width and height are properties you can access from the object ctx.drawImage(0, 0, img.width. img.height); }

Your image should appear on the upper left corner of the canvas. Now we're ready to extract some data!



No comments:

Post a Comment