如何从 html2Canvas 调整 DIV 中的 canvas 输出?

How to resize canvas output in DIV from html2Canvas?

下面的代码使用 html2canvas 截取屏幕截图,并将 base64 字符串输出到输入字段,并将屏幕截图附加到 canvas(下面的代码在片段中不起作用,但在网站上完全有效)..我尝试使用普通 HTML 和 CSS 在 <div id="output"...> 上设置宽度和高度,并搜索以找到缩放输出图像的方法,使用 JavaScript/jQuery,屏幕上的尺寸较小但没有任何效果,无论我做什么,它都会在屏幕上打印完整的宽度和高度..有人可以指导我如何解决这个问题吗?

function screenshot() {
  html2canvas(document.body, {
    background: '#fff'
  }).then(function(canvas) {

    document.body.appendChild(canvas);

    // Get base64URL
    var base64URL = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream');
    console.log(base64URL);
    document.getElementById('screenshot_input').value = base64URL;
    document
      .getElementById('output')
      .appendChild(canvas);

  });
}
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>

<button onclick="screenshot()">Take Screenshot</button


<br>
<h2>This is the Canvas</h2>
<h3>This is more Canvas</h3>
<br>

This is an input with Base64 output: <input name="screenshot" type='text' id='screenshot_input' />
<br>
<br>

Below here should be the screenshot (Not working in this Snippet but on webpage)
<div id="output" style="width: 50%; height: 50%;"></div>

我会做的是创建一个永久canvas然后我们绘制它。

在此处查看工作示例:
https://raw.githack.com/heldersepu/hs-scripts/master/HTML/screenshot.html

<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<body>
  <button onclick="screenshot()">Take Screenshot</button>
  <div id='input'>
    <h2>This is a test</h2>
    <h3>Hello World</h3> <br>
    Base64 output:
    <input name="screenshot" type='text' id='screenshot_input' /><br><br>
  </div>
  <div id="output">
    <canvas id=c width=100 height=100 style="border:1px solid #000;"></canvas>
  </div>
</body>

<script>
  const canvas = document.getElementById('c');
  const ctx = canvas.getContext('2d');

  function screenshot() {
    html2canvas(document.getElementById('input'), {
      background: '#fff'
    }).then(function(h2c) {
      var base64URL = h2c.toDataURL('image/png').replace('image/png', 'image/octet-stream');
      document.getElementById('screenshot_input').value = base64URL;
      console.log(base64URL);

      canvas.width = h2c.width/2
      canvas.height = h2c.height/2
      ctx.drawImage(h2c, 0, 0, h2c.width/2, h2c.height/2);
    });
  }
</script>

像这样我们可以调整 canvas 以及我们正在拍摄的 image/screenshot 的大小,在这种情况下,我将图像的大小缩小为原始大小的一半