Open In App

How to convert canvas graphics to image ?

In this article, we will learn how to convert the contents of the canvas to an image and download it to the download manager of the existing browser.

The Canvas graphics is used to draw the graphics with the help of the <canvas> element on the web page. It can act as a graphics container. The different methods that are facilitated by the canvas are drawing paths, boxes, circles, text, and adding images. The Canvas API provides a method to convert the canvas graphics to data URL which in terms helps us to convert an image of a particular type like JPEG or PNG etc.



Approach: The below approach will follow to convert the canvas graphics to images:

Example 1: This example describes the generation of the image using canvas graphics.






<!DOCTYPE html>
<html>
  
<head>
    <title>
          Converting the canvas graphics to image
     </title>
</head>
  
<body>
    <h1 style="color:green"
          GeeksforGeeks
      </h1>
    <h3>
        Converting the canvas graphics to image
    </h3>
    <canvas id="mycanvas"></canvas>
    <a id="downloadlink" 
       href="#" download>
        DOWNLOAD
    </a>
</body>
<script>
    var canvas = document.getElementById("mycanvas");
    var downloadlink = document.getElementById("downloadlink");
    var ctx = canvas.getContext("2d");
    ctx.strokeStyle = "yellow";
    ctx.lineWidth = 4;
    ctx.beginPath();
    ctx.arc(100,75,50,0,Math.PI*2);
    ctx.stroke();
    var imagedata = canvas.toDataURL("image/png");
    downloadlink.href = imagedata;
</script>
</html>

Output:

 

Example 2: In the below example, we will draw an arc and download it as a PNG image.




<!DOCTYPE html>
<html>
  
<head>
    <title>
        Converting the canvas graphics to image
    </title>
</head>
  
<body>
  
    <h1 style="color:green"
        GeeksforGeeks
    </h1>
    <h3>
        Converting the canvas graphics to image
    </h3>
    <canvas id="mycanvas"></canvas>
    <a id="downloadlink" 
       href="#" 
       download>DOWNLOAD</a>
</body>
<script>
    var canvas = document.getElementById("mycanvas");
    var downloadlink = document.getElementById("downloadlink");
    var ctx = canvas.getContext("2d");
    ctx.strokeStyle = "pink";
    ctx.lineWidth = 4;
    ctx.beginPath();
    ctx.arc(100,75,60,0,Math.PI);
    ctx.stroke();
    var imagedata = canvas.toDataURL("image/png");
    downloadlink.href = imagedata;
</script>
</html>

Output:

 


Article Tags :