Previously we loaded and drew an image onto the canvas. Now we can extract some data. First, declare a variable to assign the data to once it's extracted:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//we're storing our data here
var imgData;
var img = new Image();
img.src = "/img/obama.png";
img.onload = function handleLoad() {
ctx.drawImage(0, 0, img.width. img.height);
}
Then use the getImageData function to extract pixel data from the canvas once the image is loaded:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var imgData;
var img = new Image();
img.src = "/img/obama.png";
img.onload = function handleLoad() {
//important: we can only extract pixel data from the canvas, and not directly from the image object,
//so we drew the image first
ctx.drawImage(0, 0, img.width. img.height);
//getImageData takes in four parameters, here it's the same as the four from drawImage:
//x - x coordinate at which to fetch data
//y - y coordinate at which to fetch data
//width - width of pixels to fetch
//height - height of pixels to fetch
//extract data and store it into variable declared earlier.
imgData = ctx.getImageData(0, 0, img.width, img.height);
}
Now we're ready to manipulate the pixels we've extracted from the image!
No comments:
Post a Comment