将markmap生成的svg脑图转为png并下载

将markmap生成的svg脑图转为png并下载

markmap是一个非常方便的库,可以直接将md格式转为思维导图。在开发过程中我发现,目前没有将markmap生成的脑图转为png格式保存的代码或是插件。
以下是我给出的解决方案

这是一段svg标签,用来生成markmap的容器,具体生成的代码不多赘述。

 <div class="flex flex-col resBox">
        <svg style="height: 100%; width: 100%" ref="svgRef"></svg>
        <el-button @click="onSave()" id="save">另存为</el-button>
      </div>

生成并保存相关代码

const svgRef = ref(null) //获取到svg元素
  const onSave = () => { 
      const svg = svgRef.value
      const width = svg.getBoundingClientRect().width
      const height = svg.getBoundingClientRect().height
      covertSVG2Image(svg, '思维导图', width, height)
    }
    const covertSVG2Image = (node, name, width, height, type = 'png') => {
      let serializer = new XMLSerializer()
      let source = '<?xml version="1.0" standalone="no"?>\r\n' + serializer.serializeToString(node)
      let image = new Image()
      image.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(source)
      let canvas = document.createElement('canvas')
      canvas.width = width
      canvas.height = height
      let context = canvas.getContext('2d')
      context.fillStyle = '#fff'
      context.fillRect(0, 0, 10000, 10000)
      image.onload = function () {
        context.drawImage(image, 0, 0)
        let a = document.createElement('a')
        a.download = `${name}.${type}`
        a.href = canvas.toDataURL(`image/${type}`)
        a.click()
      }
    }
posted @ 2024-03-28 11:41  Mr、Kr  阅读(100)  评论(2编辑  收藏  举报