【问题标题】:Draw SVG to canvas to download as png将 SVG 绘制到画布以下载为 png
【发布时间】:2019-10-27 20:08:29
【问题描述】:

我编写了一个函数,将我的 SVG 绘制到隐藏的画布上。然后我使用 'toDataURL' 函数获取 'pngHref' 以便稍后将画布下载为 png。

我以这里给出的答案为导向: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')
      }

当我第一次调用该函数时,它不起作用。在第二次和以后它工作。再次转换(如缩放)后,它一开始不起作用,但从第二次调用它就起作用了。

【问题讨论】:

    标签: javascript d3.js svg canvas


    【解决方案1】:

    没有解决代码中可能存在的具体问题,但我找到了一个可以解决我的一般问题的库(将 svg 下载为 png) 图书馆:saveSvgAsPng

    该方法现在看起来像这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-05
      • 2016-08-27
      • 1970-01-01
      • 2020-09-27
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多