我正在建立一个叫做“HTML测试”的东西。它完全运行在JavaScript上,非常酷。
最后,会弹出一个结果框,上面写着“你的结果”,它显示了他们花了多少时间,他们得到了多少百分比,以及他们在10道题中得到了多少道。我想有一个按钮,说“捕获结果”,让它以某种方式截图或div的东西,然后只显示在页面上捕获的图像,他们可以右键单击并“另存图像为”。
我真的很愿意这样做,这样他们就可以与他人分享他们的成果。我不希望他们“复制”结果,因为他们可以很容易地改变结果。如果他们改变了图片上的内容,那好吧。
有人知道怎么做吗?
在index.html中添加此脚本
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
使用此函数获取div标签的截图
getScreenShot(){
let c = this.elem.nativeElement.querySelector('.chartContainer'); // or document.getElementById('canvas');
html2canvas(c).then((canvas:any)=>{
var t = canvas.toDataURL().replace("data:image/png;base64,", "");
this.downloadBase64File('image/png',t,'image');
})
}
downloadBase64File(contentType:any, base64Data:any, fileName:any) {
const linkSource = `data:${contentType};base64,${base64Data}`;
const downloadLink = document.createElement("a");
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
如果你希望有“另存为”对话框,只需将图像传入php脚本,它会添加适当的标题
示例:all-in-one脚本script.php
<?php if(isset($_GET['image'])):
$image = $_GET['image'];
if(preg_match('#^data:image/(.*);base64,(.*)$#s', $image, $match)){
$base64 = $match[2];
$imageBody = base64_decode($base64);
$imageFormat = $match[1];
header('Content-type: application/octet-stream');
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false); // required for certain browsers
header("Content-Disposition: attachment; filename=\"file.".$imageFormat."\";" ); //png is default for toDataURL
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".strlen($imageBody));
echo $imageBody;
}
exit();
endif;?>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js?ver=1.7.2'></script>
<canvas id="canvas" width="300" height="150"></canvas>
<button id="btn">Save</button>
<script>
$(document).ready(function(){
var canvas = document.getElementById('canvas');
var oCtx = canvas.getContext("2d");
oCtx.beginPath();
oCtx.moveTo(0,0);
oCtx.lineTo(300,150);
oCtx.stroke();
$('#btn').on('click', function(){
// opens dialog but location doesnt change due to SaveAs Dialog
document.location.href = '/script.php?image=' + canvas.toDataURL();
});
});
</script>