One of the more interesting features of canvas is the ability to manipulate images. It can be used for dynamic image synthesis or as a graphic background, as well as game interface (Sprites) and so on. External images in any format supported by the browser can be used, such as PNG, GIF or JPEG. You can even use images generated by other canvas elements on the same page as image sources.
Introducing images into canvas requires the following two basic operations:
- Get an object pointing to an HTMLImageElement or a reference to another canvas element as a source, or use an image by providing a URL
- Use the drawImage() function to draw the image onto the canvas
Let's see how it is done.
#Get the picture that needs to be drawn
The canvas API can use one of the following types as an image source:
HTMLImageElement
These images are constructed by the Image() function, or any img element
HTMLVideoElement
Use an HTML video element as your image source to grab the current frame from the video as an image
HTMLCanvas