我正在建立一个叫做“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>

就我所知你不能那样做,我可能错了。然而,我会用php这样做,使用php标准函数生成一个JPEG,然后显示图像,不应该是一个非常困难的工作,但取决于如何华丽的DIV的内容

你不能截屏:让你这样做是不负责任的安全风险。但是,你可以:

服务器端和生成图像吗 绘制一些类似画布的东西,并将其渲染为图像(在支持它的浏览器中) 使用其他绘图库直接绘制图像(速度较慢,但适用于任何浏览器)

这是一个11年前的答案。请忽略这个答案,并在这里查看其他最近的答案

据我所知,这是不可能的javascript。

你可以为每个结果创建一个截图,保存在某个地方,并在单击保存结果时指向用户。(我猜no的结果只有10,所以创建10个jpeg图像的结果不是一个大问题)