Images and drawImage()
Getting an image to display into your canvas
follows a very simple formula made up of these two steps:
- Gain access to an image source (aka an image file, another canvas element, a frame from a video element, etc.)
- Display the data from the image source to the
canvas
That’s really all there is to it, but like most things we’ve looked at so far, it’s in the details where things get a little crazy. The first detail (that also happens to be crazy) is the drawImage
method that is ultimately responsible for getting your image pixels to display on the canvas
.
Just like all of the other drawing methods we’ve seen, it operates off of our rendering context object and looks as follows:
context.drawImage(image, x, y);
The drawImage
method takes three arguments at its most basic level. The first argument refers to what we earlier called an image source. It is where we specify the image we would like to display. The second and third arguments point to the x and y position our image will be displayed in.
There is actually more to the drawImage
method than what we’ve seen so far. It has two variations with different arguments, but we’ll worry about those variations later when we stumble onto them. In the meantime, let’s take what we’ve learned so far and actually write some code to load an image.