我有一个无服务器函数,它基于作为查询参数发送的文本返回SVG。
module.exports = (req, res) => {
const { yourName } = req.query;
res.setHeader("Content-Type", "image/svg+xml");
const svg = `
<svg fill="none" viewBox="0 0 600 400" width="600" height="400" xmlns="http://www.w3.org/2000/svg">
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml">
<style>
.title {
font-size: 10vh;
font-weight: regular;
background-color: #ffddff;
}
</style>
<p class="title">Hello ${yourName}</p>
</div>
</foreignObject>
</svg>
`;
res.send(svg);
};例如,当我调用/api?yourName=world时,它将返回以下SVG;

(已部署的网址:https://vercel-test-ruddy.vercel.app/api?world)
我需要什么?
我需要将SVG作为图像返回(PNG/JPEG)。所以,我的功能应该是,
module.exports = (req, res) => {
const { yourName } = req.query;
res.setHeader("Content-Type", "image/png");
const svg = `
<svg fill="none" viewBox="0 0 600 400" width="600" height="400" xmlns="http://www.w3.org/2000/svg">
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml">
<style>
.title {
font-size: 10vh;
font-weight: regular;
background-color: #ffddff;
}
</style>
<p class="title">Hello ${yourName}</p>
</div>
</foreignObject>
</svg>
`;
res.send( svgToPng(svg) );
};
svgToPng = (svg) => {
// not defined
}我还有其他这样的问题吗?
是。有关将SVG转换为PNG的问题很少:
几乎每个答案都谈到如何将SVG转换为画布,然后将画布转换为PNG。而且答案也老得多。我们不用画布就行吗?
在我的项目中,我实际上没有html document,我只有一个.js文件(因为我知道我们需要HTML5来使用画布)。
备注
我使用维塞尔来部署我的无服务器功能,即;
部署于:这里
发布于 2021-02-20 01:05:07
到目前为止,我发现处理这个问题的最好方法是使用无头铬和截图。作为一个例子,通过使用puppeteer,我可以获得一个视图截图,如下所示,
const browser = await puppeteer.launch();
const page = await browser.newPage();
let yourName = 'world'
const svg = `
<svg fill="none" viewBox="0 0 600 400" width="600" height="400" xmlns="http://www.w3.org/2000/svg">
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml">
<style>
.title {
font-size: 10vh;
font-weight: regular;
background-color: #ffddff;
}
</style>
<p class="title">Hello ${yourName}</p>
</div>
</foreignObject>
</svg>
`;
await page.setViewport({ width: 2048, height: 1170 });
await page.setContent(svg);
console.log(await page.content());
await page.screenshot({path: 'screenshot.png'});
await browser.close();然后,就可以很容易地发送png作为响应。
发布于 2020-09-13 14:46:36
看起来像解构查询参数,在这种情况下,它在查询中搜索特定的对象属性。
如果您显式地使用yourName作为查询param,它应该可以工作。
https://vercel-test-ruddy.vercel.app/api?yourName=world
或者不要解耦req.query对象属性。
<iframe src="https://vercel-test-ruddy.vercel.app/api?yourName=world" width="450px" height="450px">
https://stackoverflow.com/questions/63871708
复制相似问题