Get the App
SLTechnology News&Howtos  ›  Development  › 

How to convert Canvas and Image to each other

Shulou Source: shulou.com Published: 2022-06-01 05:40:56 09月29日 Update

Today, I would like to share with you the relevant knowledge points about how to convert Canvas and Image into each other. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look.

Copy the code

The code is as follows:

/ / convert image to canvas object

Function convertImageToCanvas (image) {

/ / create a canvas DOM element and set its width and height to be the same as the picture

Var canvas = document.createElement ("canvas")

Canvas.width = image.width

Canvas.height = image.height

/ / coordinates (0J0) indicate that the drawing starts here, which is equivalent to offset.

Canvas.getContext ("2d") .drawImage (image, 0,0)

Return canvas

}

Convert Canvas to Image

Assuming that the image has been processed on canvas, you can use the following methods to turn canvas into a picture Image object.

Copy the code

The code is as follows:

/ / extract image image from canvas

Function convertCanvasToImage (canvas) {

/ / New Image object, which can be understood as DOM

Var image = new Image ()

/ / canvas.toDataURL returns a string of Base64-encoded URL. Of course, the browser itself certainly supports it.

/ / specify the format PNG

Image.src = canvas.toDataURL ("image/png")

Return image

}

These are all the contents of the article "how to convert Canvas and Image". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Tags: Code knowledge articles pictures objects content different large elements images coordinates most that is methods more formats browsers knowledge points coding industries Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Linux Huawei OPPO Reno macOS