Download SVG as PNG when devicePixelRatio !== 1

244 views Asked by At

I want to render an SVG to PNG.

I do this by writing the SVG to a canvas and downloading the canvas as a PNG.

When doing this on a device with a retina display and a devicePixelRatio !== 1 this results in a blurry image.

When rendering to the screen this is easily remedied by scaling the canvas up through the attributes and then scaling the canvas down through CSS.

canvas.width = width * scale;
canvas.style.width = width;

However, I want to download the canvas as a PNG with the correct resolution and size and all I can manage is to download a PNG that is twice the intended size but not blurry when scaled down or a PNG that is the correct size but blurry.

This Fiddle shows the problem, please note that you need to be on a machine with devicePixelRatio !== 1 (like a MacBook Pro or iMac).

1

There are 1 answers

0
Jorma Turkenburg On

I found the fix.

The image is just blurry because it's a raster image rendered to a screen with 4 physical pixels for every 1 pixel in the image. That's why you need to scale up the canvas by a factor of 4 (2 x 2) and then scale it down. Only then does the canvas contain a pixel for every physical pixel.

But then downloading that canvas will of course result in an image twice as wide and twice as high. That's the intended result!

My question originated from my belief that the correct image size could look that pixelated.