Comments: This article mainly introduces how to put an image in HTML5 Canvas and save it as an image. It is a very practical function to save the image content as an image. For more information, see
Copy the image to the canvas using JavaScript
To put an image into the canvas, use the drawImage method of the canvas element:
The Code is as follows:
// Converts image to canvas; returns new canvas element
Function convertImageToCanvas (image ){
Var canvas = document. createElement ("canvas ");
Canvas. width = image. width;
Canvas. height = image. height;
Canvas. getContext ("2d"). drawImage (image, 0, 0); </p> <p> return canvas;
}
The coordinates of the 0 and 0 parameters on the canvas will be copied to this place.
Save the canvas as an image in JavaScript format
If your work on the canvas has been completed, you can use the following simple method to convert the canvas data to the image format:
The Code is as follows:
// Converts canvas to an image
Function convertCanvasToImage (canvas ){
Var image = new Image ();
Image. src = canvas. toDataURL ("image/png ");
Return image;
}
This code will magically convert canvas into PNG format!
The conversion technology between images and canvases may be much simpler than you think.