【发布时间】:2019-12-06 12:10:46
【问题描述】:
我正在使用 npm 的 svg-to-image 和 get-canvas-context 包。 不使用外来对象,我可以将画布提取为 png 图像。但主要问题是我的 svg 中需要 foreignObject 来满足要求。
var svgToImage = require('svg-to-image')
var getContext = require('get-canvas-context')
// set up a new Canvas2D
var context = getContext('2d', {
width: 200, height: 200
})
var data = `<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
<style>
div {
color: white;
font: 18px serif;
height: 100%;
overflow: auto;
}
</style>
<polygon points="5,5 195,10 185,185 10,195" />
<foreignObject x="20" y="20" width="160" height="160">
<div xmlns="http://www.w3.org/1999/xhtml">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Sed mollis mollis mi ut ultricies. Nullam magna ipsum,
porta vel dui convallis, rutrum imperdiet eros. Aliquam
erat volutpat.
</div>
</foreignObject>
</svg>`;
var View = svgToImage(data, function (err, image) {
if (err) throw err
// draw image to canvas
context.drawImage(image, 0, 0)
// append to DOM
var canvas = context.canvas
window.a=document.body.appendChild(context.canvas)
// console.log(a.toDataURL('image/png'))
// open a PNG image the user can Right Click -> Save As
window.open(context.canvas.toDataURL('image/png'))
})
export default View;
【问题讨论】:
-
到底是什么问题?您在此处发布的代码是 svg-to-image 库的示例代码的略微修改版本。如果您只是复制粘贴代码并且它不起作用,那么您可能是在不支持 foreignObject 的浏览器上进行测试,如示例代码下方所述。如果这是问题所在,您难道不喜欢将所有 HTML 节点替换为它们在 SVG 中的等价物
<text>?
标签: javascript html svg canvas