Home > Web Front-end > JS Tutorial > body text

Detailed explanation of how to convert Canvas content into images using JavaScript

coldplay.xixi
Release: 2020-06-19 17:06:13
forward
6243 people have browsed it

Detailed explanation of how to convert Canvas content into images using JavaScript

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.

Use JavaScript to copy the image into the canvas

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;
}
Copy after login

Here0, 0parameter coordinate point on the canvas, the image will be copied to this place.

Use JavaScript to keep the canvas in image format

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;
}
Copy after login

This code can magically convert canvas into PNG format!

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!

Related labels:
source:webhek.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template