为什么html2canvas上面有一个白色的space?

why there is a White space on the top on html2canvas?

我的 html2canvas 上有一个白色的 space,我不确定发生了什么。到目前为止,这是我的代码。

function doFunction() {

  html2canvas(document.querySelector("#capture"), ).then(canvas => {
    $("body").append(canvas);
  });
}

$("button").click(function() {
  doFunction();
});
div {
  box-sizing: border-box;
  font-family: 'ABeeZee', sans-serif;
}

body {
  background-color: red;
}

#capture {
  width: 900px;
  height: 900px;
  background-color: aqua;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://html2canvas.hertzen.com/dist/html2canvas.js"></script>
<div id="capture">
  Hello
</div>
<button type="button">Click Me!</button>

这是附加的canvas。请注意顶部有一个白色的 space。我怎样才能删除它?

尝试将此添加到您的风格中css

*{
    margin:0;
    padding:0;
}

同时尝试清除浏览器缓存,这在大多数情况下都是问题所在。 如果这不起作用,请尝试删除所有 css 样式,然后将它们一个接一个地添加回来,看看它是何时以及如何引起的。

GitHub Issue

你应该检查文档滚动,我在页面滚动时遇到同样的问题 活动或页面向下滚动时。

尝试添加

{
    scrollX: 0,
    scrollY: -window.scrollY
}

到 html2canvas 选项

我有一个类似的问题,通过一些试验我意识到在生成 pdf 之前滚动到页面顶部可以解决它。

所以我在生成 pdf 之前添加了这一行以滚动到页面顶部并且它起作用了:

window.scrollTo(0,0);

试试这个 css

*{
     padding:0;
      margin:0;
}

以下代码对我有用

html2canvas(element , {
    scrollX: -window.scrollX,
    scrollY: -window.scrollY,
    windowWidth: document.documentElement.offsetWidth,
    windowHeight: document.documentElement.offsetHeight
})