关闭

Study JavaScript《Canvas Image相互转换》

419人阅读 评论(0) 收藏 举报
分类:

JS Canvas与Image互相转换

Convert an Image to Canvas with JavaScript

To convert an image to canvas, you use a canvas element's context's drawImage method:

// 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 arguments map to coordinates on the canvas where the image data should be placed.

Convert Canvas to an Image with JavaScript

Assuming modifications to the image have been made, you can easily convert the canvas data to image data with the following snippet:

// Converts canvas to an image
function convertCanvasToImage(canvas) {
	var image = new Image();
	image.src = canvas.toDataURL("image/png");//返回的是一串Base64编码的URL
	return image;
}

The code above magically converts the canvas to a PNG data URI!

 

注:本文摘自 http://davidwalsh.name/convert-canvas-image
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:111282次
    • 积分:1779
    • 等级:
    • 排名:千里之外
    • 原创:64篇
    • 转载:54篇
    • 译文:0篇
    • 评论:11条
    最新评论