html2canvas : 去掉图片上方空的space

html2canvas : remove empty space above the picture

这让我发疯。我只是想要 html2canvas 捕获图像

我有:

<div id="post" class="xx">Déposer</div>
<canvas width="500" height="200"></canvas>

<script type="text/javascript" src="html2canvas.js"></script>
<script type="text/javascript">
   var canvas = document.querySelector("canvas");
   html2canvas($("#post"), {canvas: canvas}).then(function(canvas) {
        var img = canvas.toDataURL()
        window.open(img); 
   });
</script>

结果是这张图片:

按钮出现在canvas的底部,我想只保留按钮,知道如何只得到按钮吗?

如果我改变 canvas 的大小,那么结果是这样的:

这里是按钮的代码:

<div id="post">
    <div style="float:left;background:url(g.png);width:21px;height:53px;"></div>
   <div id="c" style="float:left;background:url(c.png) repeat-x;height:53px;font-family:arial;text-shadow: -1px -1px rgba(0, 0, 0, 0.3);padding: 12px 20px;font-size: 20px;line-height: 24px;color: rgb(255, 255, 255);text-align: center;vertical-align: middle;text-decoration: none;">Déposer</div>
     <div style="float:left;background:url(d.png);width:21px;height:53px;"></div>
</div>

和文件:

这使得这个按钮(页面中没有额外的 css):

以下代码:

<html>
    <head>
        <style>
            canvas {
                border: solid red 1px;
            }
        </style>
    </head>
<div id="post">
    <div style="float:left;background:url(g.png);width:21px;height:53px;"></div>
   <div id="c" style="float:left;background:url(c.png) repeat-x;height:53px;font-family:arial;text-shadow: -1px -1px rgba(0, 0, 0, 0.3);padding: 12px 20px;font-size: 20px;line-height: 24px;color: rgb(255, 255, 255);text-align: center;vertical-align: middle;text-decoration: none;">Déposer</div>
     <div style="float:left;background:url(d.png);width:21px;height:53px;"></div>
</div>
    <canvas width="500" height="200"></canvas>

    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="html2canvas.js"></script>
    <script type="text/javascript">
       var canvas = document.querySelector("canvas");
       html2canvas($("#post"), {canvas: canvas});

//.then is an invalid function for html2canvas
/*.then(function(canvas) {
            var img = canvas.toDataURL()
            window.open(img);
       });
*/
    </script>
</html>

给我以下结果:

由此我得出结论

  • html2canvas 在将图像添加到 canvas
  • 的位置周围有少量填充
  • 您的按钮上可能有 css,这可能导致 canvas 将其向下推得比您希望的更远