Comment: This article shows you how to convert Image to Canvas, and how to extract an Image. The sample code is as follows. Friends with this need can refer to it. I hope it will be helpful to you.
JS Canvas and Image convert each otherOriginal Demo: JavaScript Canvas Image Conversion Demo
At last week's Mozilla Web Development Conference, we ended up spending most of the day discussing future Mozilla market applications. Instagram is the most popular mobile app recently, sold to FaceBook for a sky-high price of $1 billion.
I don't mind earning some extra money, so I decided to create an Instagram-style app (will share it later)
This article shows you how to convert Image to Canvas and how to extract an Image.
Convert Image to Canvas
To convert an image to Canvas (artboard, canvas), you can use the drawImage method of the canvas element context:
// Convert image to canvas object
function convertImageToCanvas(image) {
// Create a canvas DOM element and set its width and height the same as the picture
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
// Coordinates (0,0) indicate the drawing from 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 method to convert canvas into an image Image object.
// Extract image from canvas
function convertCanvasToImage(canvas) {
//The new Image object can be understood as DOM
var image = new Image();
// canvas.toDataURL returns a string of Base64 encoded URLs. Of course, the browser itself must support it.
// Specify the format PNG
image.src = canvas.toDataURL("image/png");
return image;
}
Uh! The conversion of image images and canvas is easier than you think. In the future, I will demonstrate different image processing technologies to you. I believe that you will definitely make a lot of money with these technologies in the future.