D3,svg图表下载图片,获取base64方法:

downloadpng () {
  var $svg = d3.select('#' + this.chartId) // 获取到d3图
  var serializer = new XMLSerializer()
  var source = '<?xml version="1.0" standalone="no"?>\r\n' + serializer.serializeToString($svg.node())
  var image = new Image()
  image.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(source)))
  image.onload = function () {
    var canvas = document.createElement('canvas')
    canvas.width = 2500
    canvas.height = 2000
    var context = canvas.getContext('2d')
    context.fillStyle = '#fff'// 设置保存后的PNG 是白色的
    context.fillRect(0, 0, 2500, 2000)
    context.drawImage(image, -3500, -3000)
    var url = canvas.toDataURL('image/png')  // 这就是得到的base64编码
    var pngName = '传播路径 ' + moment().format('YYYY-MM-DD')
    var a = document.createElement('a')
    a.download = pngName + '.png'
    a.href = url
    a.click()
复制代码
  • 私信