【发布时间】:2020-01-19 09:21:54
【问题描述】:
我正在制作一个将文本转换为图像的生成器。一切都完成了,但我需要通过单击按钮将我的反应组件转换为图像。
只是寻找提示和网站链接。
【问题讨论】:
-
昨天刚遇到这个挑战,所以写了一篇教程:From React Component to Image
标签: reactjs png jpeg react-component
我正在制作一个将文本转换为图像的生成器。一切都完成了,但我需要通过单击按钮将我的反应组件转换为图像。
只是寻找提示和网站链接。
【问题讨论】:
标签: reactjs png jpeg react-component
有很多方法可以做到这一点。
您可以使用 html2canvas 库。 示例代码 - :
html2canvas(input, {
// // dpi: 144,
backgroundColor: "#FFFFFF",
// allowTaint: false,
// taintTest: false,
})
.then((canvas) => {
console.log(canvas);
canvas.style.display = 'none';
var image = canvas.toDataURL("png")
var a = document.createElement("a");
a.setAttribute('download', 'myImage.png');
a.setAttribute('href', image);
a.click();
}
或者你也可以使用Blob来保存图片-:
canvas.toBlob(
blob => {
const anchor = document.createElement('a');
anchor.download = `${this.state.regionName}.jpeg`; // optional, but you can give the file a name
anchor.href = URL.createObjectURL(blob);
anchor.click(); // ✨ magic!
URL.revokeObjectURL(anchor.href); // remove it from memory and save on memory! ?
},
'image/jpeg',
0.9,
);
【讨论】: