Comments: This article shows you how to convert an Image to a canvas and how to extract an Image from the canvas. The sample code is as follows. For more information, see, I hope it will help you to convert JS Canvas and Image.
Original Demo: JavaScript Canvas Image Conversion Demo
At last week's Mozilla Web Development Conference, we spent half a day discussing future Mozilla market applications. Instagram is the most popular mobile app in the near future and sold it to FaceBook at a price of $1 billion.
I don't mind earning extra money, so I decided to create an Instagram-style app (which will be shared later)
This article shows you how to convert an Image to a canvas and how to extract an Image from the canvas.
Convert Image to Canvas
To convert an image to a Canvas (canvas), you can use the drawImage method of the Canvas element context:
The Code is as follows:
// Convert an image to a canvas object
Function convertImageToCanvas (image ){
// Create a canvas DOM element and set its width and height to the same image
Var canvas = document. createElement ("canvas ");
Canvas. width = image. width;
Canvas. height = image. height;
// The coordinate (0, 0) indicates that the painting starts from this point, which is equivalent to the offset.
Canvas. getContext ("2d"). drawImage (image, 0, 0 );
Return canvas;
}
Convert Canvas to Image
If the Image has been processed on the canvas, you can use the following method to convert the canvas to an Image object.
The Code is as follows:
// Extract 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 URLs. Of course, the browser certainly supports
// Specify the PNG format
Image. src = canvas. toDataURL ("image/png ");
Return image;
}
Amount! Mutual conversion between image and canvas is easier than you think. In the future, I will show you different image processing technologies. I believe you will surely make a lot of money using these technologies in the future.