It looks like OP is already doing that. Or rather, OP calls katex (https://katex.org/) to get MathML and HTML; then renders the HTML to a raster image. But he's throwing the MathML away.
KaTeX has a build in MathML feature, but I haven't yet looked into it for rendering.
The "Share text" functionality of the website uses KaTeX's MathML feature as an intermediate step.