We spent half a day last week developing the next app to be put into the Mozilla Marketplace. There is an application that is very popular right now, and that is Instagram. Facebook spent $1 million to acquire it. We also want to put $1 million in our pockets, and I decided to develop an Instagram-style application. In this article, I will introduce how to copy an image into canvas, and in turn, how to save the canvas content as an image. Format.
Watch the demo
To put the image into the canvas, we use the drawImage
method of the canvas element:
// 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); return canvas; }
Here0, 0
parameter coordinate point on the canvas, the image will be copied to this place.
If the work on your canvas has been completed, you can use the following simple method to convert the canvas data into image format:
// Converts canvas to an image function convertCanvasToImage(canvas) { var image = new Image(); image.src = canvas.toDataURL("image/png"); return image; }
This code can magically convert canvas into PNG format!
Watch Demo
These techniques for converting between images and canvases may be simpler than you think. In future articles, I will write about some techniques for applying different filters to these images.
Recommended tutorial: "javascript video tutorial"
The above is the detailed content of Detailed explanation of how to convert Canvas content into images using JavaScript. For more information, please follow other related articles on the PHP Chinese website!