【问题标题】:React ● I want to convert a react-component to a JPG or PNGReact ● 我想将 react-component 转换为 JPG 或 PNG
【发布时间】:2020-01-19 09:21:54
【问题描述】:

我正在制作一个将文本转换为图像的生成器。一切都完成了,但我需要通过单击按钮将我的反应组件转换为图像。

只是寻找提示和网站链接。

【问题讨论】:

标签: reactjs png jpeg react-component


【解决方案1】:

有很多方法可以做到这一点。

您可以使用 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,
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 2020-12-25
    • 2012-09-15
    • 2012-04-09
    • 1970-01-01
    • 2015-01-31
    • 2021-10-14
    相关资源
    最近更新 更多