🏠 back to Observable

@mbostock/saving-svg rasterize oddity


#1

Writing this post to talk through the behavior demonstrated by this notebook: https://beta.observablehq.com/@cw/rasterize-output-oddity

The notebook is a demo of behavior I noticed in another private notebook. That private notebook generates SVG which can be saved as a PNG via the rasterize function from @mbostock/saving-svg. In that private notebook, rasterization consistently excludes text elements from the rasterized output, and I’m having trouble figuring out what I’m doing wrong.

I simplified the private example down to what’s shown in https://beta.observablehq.com/@cw/rasterize-output-oddity and noticed the behavior is reproducible when font-size is below 0.5.

Maybe this has something to do with the unit-less nature of my input SVG?

I’m at a loss to explain it and haven’t figured out a workaround, so I pose the question to this channel.

Any thoughts?

Thank you,
Christian


#2

Interesting, I can reproduce what you say in Chrome, but what I get in Firefox is yet different:

.


#3

Hey Christian,

raster-svg uses Canvas to redraw SVG on a Canvas context, and browsers often take optimization steps to skip drawing steps that they believe won’t result in anything. For example, in Chrome a line of width 0.004 will render, but one at 0.003 won’t. If you set globalAlpha to c.globalAlpha = 0.001, then the following draw instructions are skipped, but at 0.002, a 0.2% alpha equivalent is used. In Chrome, a line of 0.0001 length won’t be rendered, one of 0.001 is rendered as a gradient along a line (surprise?), and 0.005 is rendered as a normal line.

So, the moral of the story is, well, there’s chaos at the extremes of the Canvas API - extremely short things, small things, and transparent things are liable to be rendered weirdly or not at all, even by mature browsers like Chrome. In this case, you’re likely running into another one of those cases, and I would mostly just recommend to use a larger viewBox and a larger SVG, so that the tricky places where your browser is running out of floating-point accuracy or making optimization decisions are avoided altogether.


#4

Thanks for the insightful response, Tom. I’ll keep your suggestions in mind going forward.

By the way, many thanks to the Observable team for sharing this platform with the world. I can’t wait to see what the future holds!

Christian