I’m currently working on a small side-project using React, where I have developed an app that displays a Tweet component that can be customized by the user to ultimately be saved as a PNG or SVG. I have a Next.js application deployed on Vercel that contains an API endpoint (that’s all I’m using this deployment) that when called, calls the Twitter API and retrieves all of the necessary data to display the Tweet component. This is working great, and the Tweet component displays just fine, the profile picture (PFP) loads no problem:
This profile picture is 48px by 48px, and is less than 10KB in size. In order to add export functionality, I am using this neat library html-to-image.
The issue is that when I export the image, all of the UI components render correctly EXCEPT for the profile picture. If I use images not from the Twitter CDN, they usually appear on this exported image. What my theory is is that it is just taking too long for Twitter to serve this image and the html-to-image
library is not waiting long enough for the image to load, so it just decides not to include it:
This is the code I am using to export the image (my onclick
function`):
import { toBlob, toPng, toSvg } from "html-to-image";
...
const onExpClick = () => {
if (ref.current === null) {
return;
}
if (exportOptions.format === "PNG") {
toBlob(ref.current, {
cacheBust: true,
width: 1100,
height: 700,
pixelRatio: exportOptions.scale,
style: {
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
backgroundImage:
"linear-gradient(135deg,#ffddc7,#ffd5c7,#ffcac8,#fecad6,#ffcde8,#ebcefc,#dfcffe,#cad5f3,#d9eafe)",
},
})
.then((blob) => {
if (blob) {
FileSaver.saveAs(blob, "tweet.png");
}
})
.catch((err) => {
console.log(err);
});
}
...
};
I am posting because I am unsure of what to do from here, as I am unaware of how front-end developers typically go about solving this problem. If it helps, the link to the profile picture is already known by the time the user presses “export”, could one way to solve this be by downloading the image to local storage and then serving it from there when its time to re-build the component to be used in an exported canvas? That way we wouldn’t have to go back out to the Twitter CDN just to get an Image we already have? Let me know what you would do. I am also willing to fork the html-to-image
module if I could achieve what I am doing from that, but so far looking into it I have not found anything that would resolve this issue and it doesn’t seem like that repository is that well maintained anymore.