As part of my Draw Something Solver, I need to be able to extract the letters from the screenshot image.
I’ve already looked at loading an image into a HTML 5 canvas object in an earlier post, so I will assume that code is already in place.
It’s actually very easy to extract part of an image from a canvas, we just need to use the
getImageData() method from the canvas context object. This takes 4 parameters, the x and y coordinates for the top left corner of the image, and width and height to extract.
var letterImageData = dsCanvasContext.getImageData(27, 782, 72, 71);
In this case, I’m cutting out a 72×71 block starting from the coordinates 27,782.
If you need to paste this extract into another canvas, or even the same canvas, you can use the
putImageData method on the canvas context object. This takes 3 parameters, the ImageData you wish to draw into the canvas, and the top left x and y coordinates to draw it into.
This will post into the top left hand corner of the original canvas.