Home  >  Article  >  Web Front-end  >  How to put pictures in HTML5 Canvas and save them as pictures_html5 tutorial tips

How to put pictures in HTML5 Canvas and save them as pictures_html5 tutorial tips

WBOY
WBOYOriginal
2016-05-16 15:47:551242browse

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:

Copy code
Code 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);

return canvas;
}


The 0, 0 parameter here is the coordinate point on the canvas, and the image will be copied to this place.

Use JavaScript to save the canvas into image format

If your work on the canvas has been completed, you can use the following simple method to convert the canvas data into image format:

Copy code
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 can magically convert canvas into PNG format!

These techniques for converting between images and canvases may be simpler than you think.

Statement:
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