【问题标题】:Unable to extract "base 64" from svg drawn in canvas using foreignobject无法从使用外来对象在画布中绘制的 svg 中提取“base 64”
【发布时间】: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 中的等价物 &lt;text&gt;

标签: javascript html svg canvas


【解决方案1】:

您在客户端使用“svg-to-img”包。 在服务器端(节点)使用相同的包

const svgToImg = require("svg-to-img");

svgToImg.from(svg).toPng({ width: dimension[0]/2, height: dimension[1]/2 })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 2020-06-16
    • 2016-03-17
    • 2014-01-29
    • 1970-01-01
    • 2022-01-15
    • 2013-01-07
    相关资源
    最近更新 更多