0

I wrote a function that draws my SVG to a hidden canvas. Then I use the 'toDataURL' function to get the 'pngHref' to download the canvas as a png later.

I oriented on the answer given here: draw svg to canvas with canvg

svgToCanvas(){
        var svg = d3.select("svg")._groups[0][0]
        var img = new Image()
        var serializer = new XMLSerializer()
        var svgStr = serializer.serializeToString(svg)

        img.src = 'data:image/svg+xml;base64,'+window.btoa(svgStr)       

        var canvas = document.getElementById('canvas-id')
        canvas.style.visibility = 'hidden' 
        canvas.width = this.width
        canvas.height = this.height

        canvas.getContext("2d").drawImage(img,0,0,this.width,this.height)

        this.options.pngHref = canvas.toDataURL('image/png')
      }

When I call the function for the first time it does not work. At second time and later it works. After a transition (like zooming) again it does not work at first but from second call on it does.

jsand3k
  • 134
  • 1
  • 4

1 Answers1

0

Does not solve the specific problem that might be in the code but I found a library that solves my general problem (to download a svg as png) Library: saveSvgAsPng

The method looks like this now:

import * as downloadAsPng from 'save-svg-as-png'
...
downloadPng(){
  var svg = d3.select("svg")._groups[0][0]
  downloadAsPng.saveSvgAsPng(svg, "download.png")
}
jsand3k
  • 134
  • 1
  • 4