I need to create a screenshot of a tweet to then store it in a PostgreSQL DB and/or show it in my webpage (show the screenshot) made in ReactJS, with Typescript. I use react-tweet-embed to show the tweet but I’m in need to store the picture of that tweet in my DB.
Does a library exist already with this available?
Advertisement
Answer
Library html2canvas allows you to capture part of a webpage on a canvas.
See: https://html2canvas.hertzen.com/
The issue you might be facing is that this library works with HTML elements. However you may give certain React elements an id, className or use ref.
JavaScript
x
20
20
1
const Capturable = ({ children }) => {
2
const divRef = useRef();
3
4
const onClick = useCallback(async () => {
5
// This canvas contains "image" of rendered element "div" and it's children
6
const canvas = await html2canvas(divRef.current);
7
// Turn it to blob and send it away
8
canvas.toBlob(blob => {
9
sendToDb(blob);
10
});
11
}, [])
12
13
return (
14
<div>
15
<div ref={divRef}>{children}</div>
16
<button onClick={onClick}>Capture!</button>
17
</div>
18
);
19
}
20
With code above
JavaScript
1
4
1
<Capturable>
2
<SomethingElseInside />
3
</Capturable>
4