是否可以捕获或打印html画布中显示的图像或pdf?

我希望通过画布生成图像,并能够从该图像生成png。


当前回答

如果您通过服务器进行下载(这样您可以命名/转换/后处理等文件),这里有一些帮助:

-使用toDataURL发布数据

-设置标题

$filename = "test.jpg"; //or png
header('Content-Description: File Transfer');
if($msie = !strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false)      
  header("Content-type: application/force-download");else       
  header("Content-type: application/octet-stream"); 
header("Content-Disposition: attachment; filename=\"$filename\"");   
header("Content-Transfer-Encoding: binary"); 
header("Expires: 0"); header("Cache-Control: must-revalidate"); 
header("Pragma: public");

-创建图像

$data = $_POST['data'];
$img = imagecreatefromstring(base64_decode(substr($data,strpos($data,',')+1)));

-将图像导出为JPEG

$width = imagesx($img);
$height = imagesy($img);
$output = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($output,  255, 255, 255);
imagefilledrectangle($output, 0, 0, $width, $height, $white);
imagecopy($output, $img, 0, 0, 0, 0, $width, $height);
imagejpeg($output);
exit();

-或透明PNG

imagesavealpha($img, true);
imagepng($img);
die($img);

其他回答

function exportCanvasAsPNG(id, fileName) {

    var canvasElement = document.getElementById(id);

    var MIME_TYPE = "image/png";

    var imgURL = canvasElement.toDataURL(MIME_TYPE);

    var dlLink = document.createElement('a');
    dlLink.download = fileName;
    dlLink.href = imgURL;
    dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':');

    document.body.appendChild(dlLink);
    dlLink.click();
    document.body.removeChild(dlLink);
}

如果您正在使用jQuery(很多人都这么做),那么您可以这样实现接受的答案:

var canvas = $("#mycanvas")[0];
var img = canvas.toDataURL("image/png");

$("#elememt-to-write-to").html('<img src="'+img+'"/>');

从<canvas/>上载图像:

async function canvasToBlob(canvas) {
  if (canvas.toBlob) {
    return new Promise(function (resolve) {
      canvas.toBlob(resolve)
    })
  } else {
    throw new Error('canvas.toBlob Invalid')
  }
}

await canvasToBlob(yourCanvasEl)

HTML5提供Canvas.toDataURL(mimetype),它在Opera、Firefox和Safari4测试版中实现。然而,有许多安全限制(主要是与将内容从另一个来源绘制到画布上有关)。

因此,您不需要额外的库。

e.g.

 <canvas id=canvas width=200 height=200></canvas>
 <script>
      window.onload = function() {
          var canvas = document.getElementById("canvas");
          var context = canvas.getContext("2d");
          context.fillStyle = "green";
          context.fillRect(50, 50, 100, 100);
          // no argument defaults to image/png; image/jpeg, etc also work on some
          // implementations -- image/png is the only one that must be supported per spec.
          window.location = canvas.toDataURL("image/png");
      }
 </script>

理论上,这应该创建一个中间有绿色方块的图像,然后导航到该图像,但我还没有进行测试。

最初的答案是针对一个类似的问题。已修订如下:

const canvas = document.getElementById('mycanvas')
const img    = canvas.toDataURL('image/png')

使用IMG中的值,您可以将其写入新图像,如下所示:

document.getElementById('existing-image-id').src = img

or

document.write('<img src="'+img+'"/>');