How to convert SVG to PNG and then to clipboard?

1.1k views Asked by At

I have a Js library that generates git as a graph, but sadly only in svg. I want to quickly use it as png file in clipboard to copy paste in my markdown documentation. I have successfully converted to png, but from there I am unable to take it to clipboard. The image has base64 with svg tag, though I can right click and copy that. But I want to directly copy this svg as png to clipboard. Kindly help. Below is my code.

 // Get the graph container HTML element.
    const graphContainer = document.getElementById("graph-container");

    // Instantiate the graph.
    // const gitgraph = GitgraphJS.createGitgraph(graphContainer);
    const gitgraph = GitgraphJS.createGitgraph(graphContainer, {
      orientation: 'vertical-reverse',
      author: 'Parthi <mailto:[email protected]>'
    });

    // Simulate git commands with Gitgraph API.
    const master = gitgraph.branch("master");


    master.commit("Initial commit").tag("Exercise starts here");
    master.commit({ subject: "A updates modify_me.md", author: 'A <[email protected]>' });
    master.commit({ subject: "B updates modify_me.md", author: 'B <[email protected]>' });
    master.commit({ subject: "C updates modify_me.md", author: 'C <[email protected]>' }).tag("Exercise ends here");




    function svgToPng2() {
      /*
      http://jsfiddle.net/8j8p2uyk/
      */
      var svg = $("div").find('svg')[0];
      svgSize = svg.getBoundingClientRect();
      svgData = new XMLSerializer().serializeToString(svg);
      img = document.createElement('img');
      base64Image = '<img src="data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgData))) + '"/>';

      $(base64Image).appendTo('body');

    }
    
    function png2Cb()
    {
    
      /*How to do? */
    
    }
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@gitgraph/js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="//d3js.org/d3.v4.min.js"></script>
  </head>

<body>
  <!-- DOM element in which we'll mount our graph -->
  <div id="graph-container"></div>

  <br><br>
  <!-- Transfer svg to png -->
  <button onclick="svgToPng2()">1. Convert to Png (Working)</button>
  <button onclick="png2Cb()">2. Copy that Png to clipboard (how?)</button>
  <br><br>
  Generated image: <br><br>
</body>
</html>

The first button works as I said, and I am lost in 2nd part - copying that png image to clipboard.

0

There are 0 answers