Study JavaScript《Canvas Image相互转换》

来源:互联网 发布:mac如何打人民币符号 编辑:程序博客网 时间:2024/05/23 01:22

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 elementfunction 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 imagefunction convertCanvasToImage(canvas) {var image = new Image();image.src = canvas.toDataURL("image/png");//返回的是一串Base64编码的URLreturn image;}

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

 

注:本文摘自 http://davidwalsh.name/convert-canvas-image
0 0
原创粉丝点击