简体   繁体   English

将SVG绘制到画布以下载为png

[英]Draw SVG to canvas to download as png

I wrote a function that draws my SVG to a hidden canvas. 我编写了一个将SVG绘制到隐藏画布的函数。 Then I use the 'toDataURL' function to get the 'pngHref' to download the canvas as a png later. 然后我使用'toDataURL'函数来获取'pngHref'以便稍后下载画布作为png。

I oriented on the answer given here: draw svg to canvas with canvg 我根据这里给出的答案: 使用canvg将svg绘制到画布上

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. 在转换(如缩放)后,它首先不起作用,但从第二次调用开始。

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 不解决代码中可能存在的具体问题,但我发现了一个解决我的一般问题的库(将svg下载为png)库: 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")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM