傻大专栏

傻大之成長經历

Study JavaScript《Canvas Image相互转换》

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
阅读更多
个人分类: JQuery/JS
想对作者说点什么? 我来说一句

HTML5 Canvas

2013年03月21日 244KB 下载

Canvas中的drawImage

Canvas drawImage

zhaoruda zhaoruda

2017-04-18 22:17:38

阅读数:3027

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭