The key to this is a
fancier use of
drawImage.
We've used drawImage before like this:
ctx.drawImage(MyImg, x, y);
All pretty straightforward -- drawImage takes
three parameters, being the image we want to draw, and the x & y position on the canvas where we want to draw it.
But there's a fancier form of drawImage that accepts seven parameters:
- The image we want to draw
- The x & y position within the image, for the portion of the image we want to draw
- The height and width of the portion of the image we want to draw
- The x & y position on the canvas where we want to draw the portion
- The height and width on the canvas we want the portion to fill
We don't actually need the last pair of parameters, but the rules of Javascript demand we have to provide them.