Hi there!
It's common in some situations, we would like to convert a text inside a card to SVG, like example: creating avatars, or optimizing information and pass the SVG as og:image, etc. There are a multitude of situations that we can solve by converting HTML to SVG.
Satori
tl;dr: a library used to generate SVG from HTML and CSS. Using React, you can pass it as JSX to Satori and an SVG string results. It's simple and amazing!
See the magic!
To resolve this, you can use this function below:
import satori from 'satori';
export const GenerateSVG = async () => {
const roboto = fetch('/Roboto-Regular.ttf').then((res) => res.arrayBuffer());
return await satori(
<div style={{
height: '100%',
width: '100%',
display: 'flex',
textAlign: 'center',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
flexWrap: 'nowrap',
fontSize: "22px",
backgroundColor: 'white',
backgroundSize: '100px 100px',
}}>
<div
style={{
display: 'flex',
justifyContent: 'center',
border: "2px solid #fff",
backgroundColor: "green",
color: "#FFF",
fontWeight: 700,
fontSize: "50px",
borderRadius: "50%",
padding: "50px",
}}
>
IS
</div>
</div>,
{
width: 600,
height: 400,
fonts: [
{
name: 'Roboto',
data: await roboto,
weight: 400,
style: 'normal',
},
],
},
)
}
In the example above, I used static text with the initial letters of my name, but if you want to make it dynamic, just pass it as props.
You can style it however you want!
In this case, to show how it works, I'll do a demonstration below, forcing the use of SVG in a very simple div.
function App() {
const [SvgImage, setSvgImage] = useState()
useEffect(() => {
(async () => {
const Svg = await GenerateSVG();
setSvgImage(Svg);
})();
}, []);
return (
<div className="App">
<div dangerouslySetInnerHTML={{ __html: SvgImage }} />
</div>
)
}
export default App;
And that's it! An avatar just like Microsoft Teams.
twitter: https://twitter.com/@X8ING_
github: github.com/italosantana
Top comments (0)