When I started blogging three and a half years ago, I quickly realized that I needed some way to embed equations into my blog posts. No solution existed at that time; although, there were several implementations of equation renderers for websites. I eventually put together an algorithm that processed LaTeX equations through latex, dvips, and ghostscript to produce png images containing the equations. I also wrote some post-processing that would allow the equations to be properly aligned with text: . (I found the idea in one of the several rendering projects that I looked at, and improved on it.) My text processor for Movable Type, KwickXML, has included my equation rendering code from the beginning. I recently updated/rewrote KwickXML and have rewritten my equation rendering code simplifying and improving the algorithm.
I now just run the equation through pdflatex, generating a pdf file that I then post-process. I no longer use latex to add color to the equation, instead I do that in the post-processing. On rendering, pdflatex produces a white equation on a black background, which I use as a mask in post-processing. When paired with another image, the white on black mask determines how opaque the pixels in the first image are, producing smooth, alpha blending. (Note that the following example may not work on browsers that don’t support pngs with alpha transparency: *cough* IE6 *cough*.)
The image with alpha transparency blend seamlessly with both background colors. The image with pixel transparency only looks good on the white background. Its nice anti-aliasing falls apart when it is placed on a color different than the one it was designed for—in this case white.
When using equations in webpages, it is difficult to align them properly with the text: . Out of the many options for vertical alignment in CSS, I decided to go with “vertical-align: middle”. However, not all equations display properly under such vertical alignment: a+e=c () and a+q=g ().
To properly align the equations with text on the webpage, I need to determine the “mean line” of the text and add space either above or below the rendered equation so that mean line is at the middle of the final image. To accomplish this, I add a dash before the equation, which will appear on the mean line:
I then process the image, using the dash to determine where the middle of the image should be and add any space as needed, remove the dash, and produce the final mask.
Putting it all together, we have the complete algorithm:
- insert equation into a LaTeX template
- render with pdflatex
- trim image, removing extra blank space
- use dash to detect the “mean line”
- remove dash and trim again
- add space above or below image to make the dash line in the middle of image
- compose the mask onto the foreground color with the “CopyOpacity” option
- compose that image over the background color
- save image