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

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


当前回答

从<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)

其他回答

从<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)

我会使用“wkhtmltopdf”。它工作得很好。它使用webkit引擎(在Chrome、Safari等中使用),并且非常容易使用:

wkhtmltopdf stackoverflow.com/questions/923885/ this_question.pdf

就是这样!

试试看

您可以使用jspdf将画布捕获为图像或pdf,如下所示:

var imgData = canvas.toDataURL('image/png');              
var doc = new jsPDF('p', 'mm');
doc.addImage(imgData, 'PNG', 10, 10);
doc.save('sample-file.pdf');

更多信息:https://github.com/MrRio/jsPDF

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

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+'"/>');

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

-使用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);