【发布时间】:2018-10-25 08:22:48
【问题描述】:
我正在寻找可以帮助我将 HTML DOM 节点元素转换为图像/png 文件的库或代码 sn-p。
我尝试使用html2canvas 库,但它不渲染svg 节点,并且在我当前的项目中我有很多。我还尝试使用 canvg 库将页面上的所有 SVG 元素转换为 Canvas 元素,但 canvg 总是在渲染步骤中抛出错误:
Uncaught (in promise) TypeError: Cannot read property 'ImageClass' of 未定义
用于将 SVG 转换为 Canvas 的代码 sn-p:
export const svgToCanvas = () => {
const print = document.getElementsByClassName('print-page')[0]
const svgElements = print.getElementsByTagName('svg')
_.each(svgElements, e => {
let xml
const canvas = document.createElement('canvas')
canvas.className = 'screenShotTempCanvas'
xml = (new window.XMLSerializer()).serializeToString(e)
xml = xml.replace(/xmlns=http:\/\/www\.w3\.org\/2000\/svg/, '')
canvg(canvas, xml)
e.parentNode.insertBefore(canvas, e.nextSibling)
e.classList.add('tempHide')
e.style.display = 'none'
})
const temps = document.getElementsByClassName('.screenShotTempCanvas')
_.each(temps, e => {
e.remove()
})
const svgs = document.getElementsByClassName('tempHide')
_.each(svgs, e => {
if (e) {
e.style.display = 'block'
e.classList.remove('tempHide')
}
})
}
canvg 代码的这一行抛出错误:
if (nodeEnv) {
if (!s || s === '') {
return;
}
ImageClass = opts['ImageClass']; //<= error throws here
CanvasClass = target.constructor;
svg.loadXml(target.getContext('2d'), s);
return;
}
我还尝试使用 jsPDF 和 html-pdf 库将节点转换为 PDF 格式,但在这种情况下,所有样式都会从节点中消失,我需要它们不要丢失。
谁能提供适当的方法来将 HTML DOM 节点(富含 SVG 元素)转换为图像?
【问题讨论】:
标签: javascript html svg canvas html2canvas