How to convert a React Component to an Image
Asked Answered
T

2

6

I am making a generator for converting text into an image. Everything is done, but I need to convert my react-component to an image with a button click.

Just looking for tips and links to websites.

Tisiphone answered 18/9, 2019 at 12:6 Comment(2)
try: npmjs.com/package/html-to-imageLot
Just had this challenge yesterday, so I wrote a tutorial about it: From React Component to ImageConcentration
W
4

there are a lot of ways to do it.

you can use html2canvas library. Sample code - :

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();
    }

Or you can also use Blob to save the image -:

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,
);
Writein answered 3/9, 2020 at 7:49 Comment(0)
C
0

react-export-image is a library that can do this.

Example code is on their npmjs page.

Crush answered 29/9, 2022 at 17:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.