Html 如何截取画布的屏幕截图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16792805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 08:49:47  来源:igfitidea点击:

How to take screenshot of canvas?

javascripthtmlcanvas

提问by Герай Суинов

how to take screenshot of canvas?

如何截取画布的屏幕截图?

or How create image, which will consist of image + free zone , located on canvas?

或如何在画布上创建由图像 + 自由区组成的图像?

回答by Dominic Green

It depends what you want to do, the easiest way is to use toDataUrl on your canvas.

这取决于您想要做什么,最简单的方法是在画布上使用 toDataUrl。

canvas.toDataURL('png')

This will encode your canvas to base64, then you could use it in a download link like this

这会将您的画布编码为 base64,然后您可以在这样的下载链接中使用它

<a href="%dataURI%" download>download</a>

Or just stick it back into the dom in an image tag.

或者只是将它贴回到图像标签中的 dom 中。

You can then write a controller which is more backend using what ever language to convert that base64 to an image file if you wanted to store an actual copy off the image.

然后,如果您想从图像中存储实际副本,您可以使用任何语言编写一个更后端的控制器,以将该 base64 转换为图像文件。

See this post for more info

查看此帖子了解更多信息

How to save a PNG image server-side, from a base64 data string

如何从 base64 数据字符串保存 PNG 图像服务器端

回答by Cybermaxs

It depends on your framework but basically you can use canvas.toDataURL()

这取决于您的框架,但基本上您可以使用 canvas.toDataURL()

Here is a complete example

这是一个完整的例子

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      // draw cloud
      context.beginPath();
      context.moveTo(170, 80);
      context.bezierCurveTo(130, 100, 130, 150, 230, 150);
      context.bezierCurveTo(250, 180, 320, 180, 340, 150);
      context.bezierCurveTo(420, 150, 420, 120, 390, 100);
      context.bezierCurveTo(430, 40, 370, 30, 340, 50);
      context.bezierCurveTo(320, 5, 250, 20, 250, 50);
      context.bezierCurveTo(200, 5, 150, 20, 170, 80);
      context.closePath();
      context.lineWidth = 5;
      context.fillStyle = '#8ED6FF';
      context.fill();
      context.strokeStyle = '#0000ff';
      context.stroke();

      // save canvas image as data url (png format by default)
      var dataURL = canvas.toDataURL();
    </script>
  </body>
</html>

dataUrl will contains the image and you can save it wherever you want.

dataUrl 将包含图像,您可以将其保存在您想要的任何位置。