为什么图像不是 div 的一部分?如何添加到DOM?

Why is the image is not part of the div ? How to add it to DOM?

我在"rightcontainer"div里面只有一个按钮和一张图片。当我点击按钮时,它应该截图到 div。它确实如此,但图像不仅仅显示文字。我读到了,我认为是因为图像不在 div DOM 中。如何使图像成为 div 的一部分,以便它也出现在屏幕截图中。

$(".drag").draggable();
$(".drag").droppable();
var takeScreenShot = function() {
  html2canvas(document.getElementById("container"), {
    onrendered: function(canvas) {
      var tempcanvas = document.createElement('canvas');
      tempcanvas.width = 350;
      tempcanvas.height = 350;
      var context = tempcanvas.getContext('2d');
      context.drawImage(canvas, 112, 0, 288, 200, 0, 0, 350, 350);
      var link = document.createElement("a");
      link.href = tempcanvas.toDataURL('image/jpg'); //function blocks CORS
      link.download = 'screenshot.jpg';
      link.click();
    }
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>

<button onclick="takeScreenShot()">Snapshot</button>
<div id="container">
    <div id="leftmenu">
      Left Side
      <div class="drag">
      </div>
      <div class="drag">
      </div>
      <div class="drag">
      </div>
      Drag----------->
            &
      Click Snapppppppppppppp </br>
        
    </div>
    <div id="rightcontainer">
        Right Side
        <img id = "conn" src="https://static.pexels.com/photos/39803/pexels-photo-39803.jpeg" width="500px" ;>

    </div>


</div>

这里的问题是图像来自外部网站。 html2canvas 将只处理来自与 HTML 文件相同来源的图像,即相同的网络域。

此问题的潜在解决方法是使用某种代理,但最好的解决方案可能是只下载图像并将其与您的网站一起提供。

您可以阅读更多关于 html2canvas 的 documentation website (this issue is listed under the "Limitations" section), and if you are interested in using a proxy to resolve this matter, they are discussed here


其次,您使用的是旧版本的 html2canvas。下载 latest version,然后用这个版本替换你的 takeScreenShot 函数(因为新的 API 使用承诺,而不是回调):

var takeScreenShot = function() { 
    html2canvas(document.getElementById("container")).then(canvas=>{
        var link = document.createElement("a");
        link.href = canvas.toDataURL('image/jpg');
        link.download = 'screenshot.jpg';
        link.click();
    })
}

这将创建正确的输出(您可以通过在 var link 行之前执行 document.body.appendChild(canvas) 来测试),但是您将无法下载它,因为 canvas将是 "tainted"。要解决此问题,您必须 运行 将站点从某种本地服务器上移除(如果您还没有),例如 XAMPP.