DEV Community

swift king
swift king

Posted on

Canvas drawImage() Took Me 3 Days to Get Right

Last month I spent three days debugging why my SVG-to-PNG converter produced black-background PNGs from transparent SVGs.

The Problem

Rendering SVG to Canvas, exporting via toBlob(). Every transparent SVG came out with a black background.

What Fixed It

Not globalCompositeOperation. Not pixel manipulation. One line:

ctx.clearRect(0, 0, canvas.width, canvas.height);
Enter fullscreen mode Exit fullscreen mode

The default canvas is transparent, but drawImage blends with existing context.

Testing

200 random SVGs — Figma exports, Illustrator files, inline SVGs. 198 passed. The 2 failures used which Canvas cannot render (MDN limitation).

Bonus: imageSmoothingEnabled

For pixel-exact exports at non-native sizes, set imageSmoothingEnabled = false. W3C Canvas spec section 4.12.5.1.13.

I use these fixes in browser-local converters at svg2png.org, genbarcode.org, webp2png.io. All process without server uploads.

Curious what Canvas issues you've battled with.

Top comments (0)