How to save HTML Canvas as image using canvas.toDataURL()?

王林
Release: 2023-08-28 20:41:13
forward
1336 people have browsed it

如何使用canvas.toDataURL()将HTML Canvas保存为图像?

Use the toDataURL() method to get the image data URL of the canvas. It converts the drawing (canvas) to a 64-bit encoded PNG URL.

Example

You can try running the following code to save the canvas as an image −

<!DOCTYPE HTML>
<html>
   <head>
   </head>
   <body>
      <canvasid = "newCanvas" width = "450" height = "300"></canvas>
      <script>
         var canvas = document.getElementById(&#39;newCanvas&#39;);
         var ctx = canvas.getContext(&#39;2d&#39;);
         // draw any shape
         ctx.beginPath();
         ctx.moveTo(120, 50);
         ctx.bezierCurveTo(130,100, 130, 250, 330, 150);
         ctx.bezierCurveTo(350,180, 320, 180, 240, 150);
         ctx.bezierCurveTo(320,150, 420, 120, 390, 100);
         ctx.bezierCurveTo(130,40, 370, 30, 240, 50);
         ctx.bezierCurveTo(220,7, 350, 20, 150, 50);
         ctx.bezierCurveTo(250,5, 150, 20, 170, 80);
         ctx.closePath();
         ctx.lineWidth = 3;
         ctx.fillStyle =&#39;#F1F1F1&#39;;
         ctx.fill();
         ctx.stroke();
         var dataURL =canvas.toDataURL();
      </script>
   </body>
</html>
Copy after login

The above is the detailed content of How to save HTML Canvas as image using canvas.toDataURL()?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template