1、背景
在一些可视化平台,或者canvas、svg元素用到的地方。业务都可能会提出这样的需求,当前所展示的东西我想导出图片进行查阅;
2、svg转png图片并下载
exportImg() {
let that = this
let serializer = new XMLSerializer()
let svg = document.getElementById('svg')
let toExport = svg.cloneNode(true) // 设置为 true,克隆节点及其属性,以及后代
let bb = svg.getBBox() //
toExport.setAttribute('viewBox', bb.x + ' ' + bb.y + ' ' + bb.width + ' ' + bb.height) // 所有svg充满画布
toExport.setAttribute('width', bb.width)
toExport.setAttribute('height', bb.height)
let source = `<?xml version="1.0" standalone="no"?>\r\n` + serializer.serializeToString(toExport)
let image = new Image
image.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(source)
let canvas= document.createElement('canvas')
canvas.width = bb.width + 40
canvas.height = bb.height + 40
let context = canvas.getContext('2d')
context.fillStyle = '#fff'
context.fillRect(0, 0, 10000, 10000)
image.onload = function() {
context.drawImage(image, 20, 20) // canvas画图片,image base64数据
let a = document.createElement('a')
a.download = `${that.name}.png`
a.href = canvas.toDataURL('image/png')
a.click()
}
}
}