官方网址
API

引用方式

  1. nstall NPM
  2. npm install --save html2canvas
  3. Install Yarn
  4. yarn add html2canvas
  5. Script src
  6. http://html2canvas.hertzen.com/dist/html2canvas.js
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <script src="./html2canvas.js"></script>
  7. </head>
  8. <body>
  9. <div id="view" style="border:1px solid red;">
  10. <img src="./pl-user.png" alt="">
  11. <input type="button" value="截图" onclick="takeScreenshot()">
  12. </div>
  13. </body>
  14. <script type="text/javascript">
  15. function takeScreenshot() {
  16. /*domId 配置参数 */
  17. html2canvas(document.getElementById('view'), {
  18. backgroundColor: "#fff",
  19. useCORS: true // 如果截图的内容里有图片,可能会有跨域的情况,加上这个参数,解决文件跨域问题
  20. // width: 300,
  21. // height: 300
  22. }).then((canvas) => {
  23. //把截的图显示在网页上
  24. document.body.appendChild(canvas);
  25. //点击截图下载到本地
  26. let url = canvas.toDataURL("image/png");
  27. let a = document.createElement("a");
  28. a.href = url;
  29. a.download = "二维码";
  30. a.click();
  31. });
  32. }
  33. </script>
  34. </html>
  • 截图上传到服务器

    1. html2canvas(document.getElementById('view'), {
    2. backgroundColor: "#fff",
    3. // width: 300,
    4. // height: 300
    5. }).then((canvas) => {
    6. let base64 = canvas.toDataURL("image/png"); // 先转化为base64
    7. /* 将html2canvas生成截图上传到服务器 */
    8. let bstr = atob(base64.split(',')[1]); // atob是将base64编码解码,去掉data:image/png;base64,部分
    9. let n = bstr.length;
    10. let u8arr = new Uint8Array(n);
    11. while (n--) {
    12. u8arr[n] = bstr.charCodeAt(n);
    13. }
    14. let file2 = new File([u8arr], 'a.jpg', {type: 'image/jpg'})
    15. var formData = new FormData();
    16. formData.append("file", file2);
    17. });