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