屏幕截图是在 html2canvas() 中制作的?

Where the screenshot is being made in the html2canvas()?

我正在尝试通过 php 或 ajax 将屏幕截图上传到服务器。但我无法弄清楚在 html2canvas() 中截屏的位置?我已经搜索过但没有找到解决方案。请查看我的代码并指导我。

JS代码

$(function () {
  $("#btnSave").click(function () {
    html2canvas($("#widget"), {
      onrendered: function (canvas) {
        theCanvas = canvas;
        var image = canvas.toDataURL("image/jpeg");
        $('#captured_img').attr("src", image);
        $('#img_val').attr("value", image);
      }
    });
  });

HTML代码

<div id="widget" class="widget">
  <h1>THE IMAGE</h1>
</div>
<input type="hidden" name="img_val" id="img_val" value=""/>
<div id="showImage">
  <img id="captured_img" src="" height="120" width="100"/>
</div>
<input type="button" id="btnSave" value="Save PNG"/>

您的图像不是在任何文件系统中创建的,它只是分配给图像源的 base64 编码字符串 canvas.toDataURL("image/jpeg");。 您可以将该字符串发送到 ajax 调用并在 php 函数中创建一个文件。有关如何从 base64 字符串创建图像的更多详细信息,请参见 link dataurl to image for download in php

image/jpeg does not support a transparent background, use image/png

html2canvas will return you canvas of your DOM, you can get base64 data using toDataURL method of canvas. To upload base64 as image, you need to decode the base64 data. file_put_contents Write a string to a file.

Use following script:

PHP 脚本:

<?php
if (isset($_REQUEST['data'])) {
    $img = $_REQUEST['data'];
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $file = rand(0000000, 1131231) . '.png';
    $success = file_put_contents($file, $data);
    if ($success!==false) {
        echo 'done';
    } else {
        echo 'failed';
    }
}

HTML & JS:

$(function() {
  $("#btnSave").click(function() {
    html2canvas(document.getElementById('widget'), {
      onrendered: function(canvas) {
        var image = canvas.toDataURL("image/png");
        $('#captured_img').attr("src", image);
        $('#img_val').attr("value", image);
        $.post("decode.php", {
            data: image
          })
          .done(function(data) {
            alert("Status: " + data);
          });
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="widget" class="widget">
  <h1>THE IMAGE</h1>
</div>
<input type="hidden" name="img_val" id="img_val" value="" />

<div id="showImage">
  <img id="captured_img" src="" height="120" width="100" />
</div>
<input type="button" id="btnSave" value="Save PNG" />