使用html2canvas,由html转换canvas时,出现图片丢失问题解决方案

    在img标签上加上crossorigin="anonymous";
    如果是图片地址是跨域网址,请将图片转换为base64格式;

源码如下:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>html2canvas example</title>
  </head>

  <body>
    <div id="view">
      <input type="button" value="截图" onclick="takeScreenshot()" />
      <img
        src=""
        alt=""
        crossorigin="anonymous"
        class="imgs"
      />
      <canvas id="myCanvas"></canvas>
    </div>
  </body>
  <script src="https://unpkg.com/html2canvas@1.0.0-rc.7/dist/html2canvas.js"></script>
  <script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.fillStyle = "#FF0000";
    ctx.fillRect(0, 0, 80, 100);
    function takeScreenshot() {
      html2canvas(document.querySelector("#view")).then((canvas) => {
        document.body.appendChild(canvas);
      });
    }
    getBase64Image('https://profile.csdnimg.cn/B/1/0/3_qq_39045645',document.querySelector('.imgs'));
    
    function getBase64Image(url, ref) {
      var image = new Image();
      image.src = url + "?v=" + Math.random(); // 处理缓存
      image.crossOrigin = "*"; // 支持跨域图片
      image.onload = function () {
        var base64 = drawBase64Image(image);
        ref.src = base64;
      };
    }
    
    function drawBase64Image(img) {
      var canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, img.width, img.height);
      var dataURL = canvas.toDataURL("image/png");
      return dataURL;
    }
  </script>
</html>



图片丢失是因为这个原因

 

作者:Vam的金豆之路

主要领域:前端开发

我的微信:maomin9761

微信公众号:前端历劫之路