原生JS 將canvas生成圖片
阿新 • • 發佈:2019-03-07
converts web uri inf err function export failed exported
核心代碼:
<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" 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>
參考鏈接:
[link](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image)
[link](https://stackoverflow.com/questions/20424279/canvas-todataurl-securityerror)
[link](https://www.jianshu.com/p/6fe06667b748)
原生JS 將canvas生成圖片