Articles in this section
Category / Section

How to copy and paste a chart using base64 encoding?

2 mins read

Description

This article explains how to copy and paste a chart by converting it into a base64-encoded image.

Solution

You can copy a chart by converting its SVG element into a base64-encoded image. This method involves rendering the chart as an image using a canvas, which can then be reused in other files or applications.

Code Snippet

document.getElementById('btn').onclick = function () {
       var svg = document.querySelector("#container_svg");
       var svgData = new XMLSerializer().serializeToString(svg);
       var canvas = document.createElement("canvas");
       document.body.appendChild(canvas);
       var svgSize = svg.getBoundingClientRect();
       canvas.width = svgSize.width;
       canvas.height = svgSize.height;
       var ctx = canvas.getContext("2d");
       var img = document.createElement("img");
       img.setAttribute("src", "data:image/svg+xml;base64," + btoa(svgData));
       img.onload = function () {
           ctx.drawImage(img, 0, 0);
           var imagedata = canvas.toDataURL("image/png");
           console.log(imagedata);
           canvas.remove();
       };
   };

The following image illustrates the output of the above code.

KB4.png

View Sample in Stackblitz

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied