核心代码:
<script type="text/javascript"> // 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; } // Converts canvas to an image function convertCanvasToImage(canvas) { var image = new Image(); image.src = canvas.toDataURL("image/png"); return image; } </script>
需要注意:
跨域的图片需要设置crossOrigin="Anonymous"属性,然后等图片加载完成后才能使用 toDataURL() 方法
否则会报错:
Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
图片转canvas画布的时候(convertImageToCanvas)
需要注意的是:
如果图片原尺寸是200px*200px, 通过样式改变图片的宽高,则 image.width 和 image.height 获取的是改变后的宽高
如果改变后的宽高小于原尺寸,那么将不能完整的把图片完整的绘制出来
因为drawImage(image, 0, 0)是根据图片原尺寸进行绘制的
示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> /*img { width: 100px; }*/ </style> </head> <body> <!--<img id="tulip" src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2256920272,2188849592&fm=26&gp=0.jpg" alt="" crossOrigin="Anonymous">--> <img id="tulip" src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=158393800,2846304514&fm=26&gp=0.jpg" alt="" crossOrigin="Anonymous"> </body> </html> <script> // 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; } // Converts canvas to an image function convertCanvasToImage(canvas) { var image = new Image(); image.src = canvas.toDataURL("image/png"); return image; } function drawImage(img) { var cs = convertImageToCanvas(img); var image = convertCanvasToImage(cs); document.body.appendChild(image); } window.onload = function () { var img = document.getElementById("tulip"); img.onload = drawImage(img); } </script>
参考链接: