Home  >  Article  >  Web Front-end  >  About the mutual conversion between Canvas and Image

About the mutual conversion between Canvas and Image

不言
不言Original
2018-06-22 15:10:151665browse

This article shows you how to convert Image to canvas, and how to extract an Image from canvas. The sample code is as follows. Friends who have this need can refer to it. I hope it will be helpful to everyone. JS Canvas and Image conversion
Original text demonstration: JavaScript Canvas Image Conversion Demo
In the Mozilla Web Development Conference last week, we spent most of the day discussing future Mozilla market applications. Instagram, the most popular mobile application in recent times, was sold to FaceBook for a whopping $1 billion.
I don’t mind making some extra money, so I decided to create an Instagram style application (will share it later)

This article shows you how to convert Image to canvas, and how canvas extracts an Image .

Convert Image to Canvas

To convert the image to Canvas (artboard, canvas), you can use the drawImage method of the canvas element context:

// 把image 转换为 canvas对象 
function convertImageToCanvas(image) { 
// 创建canvas DOM元素,并设置其宽高和图片一样 
var canvas = document.createElement("canvas"); 
canvas.width = image.width; 
canvas.height = image.height; 
// 坐标(0,0) 表示从此处开始绘制,相当于偏移。 
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 a picture Image object.

// 从 canvas 提取图片 image 
function convertCanvasToImage(canvas) { 
//新Image对象,可以理解为DOM 
var image = new Image(); 
// canvas.toDataURL 返回的是一串Base64编码的URL,当然,浏览器自己肯定支持 
// 指定格式 PNG 
image.src = canvas.toDataURL("image/png"); 
return image; 
}

Well! Converting images to canvas is easier than you think. I will demonstrate different image processing technologies to you in the future. I believe you will definitely be able to make money using these technologies in the future. Big money.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

html5 How to achieve the animation effect of picture rotation

HTML5 contenteditable attribute analysis

The above is the detailed content of About the mutual conversion between Canvas and Image. For more information, please follow other related articles on the PHP Chinese website!

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