Size a canvas image preview for the pixels it actually uses

●8
calendar_today ago • schedule1 min read

A preview can take up the right space on the page and still look blurry. For a canvas that displays at 360 by 240 CSS pixels on a screen with a device pixel ratio of 2, use a backing store of 720 by 480 pixels. Keep the CSS size at 360 by 240.

Multiply each measured CSS dimension by the device pixel ratio and round the results. At a ratio of 1.25, the same box needs 450 by 300 backing pixels. If it shrinks to 300 by 200 at a ratio of 2, resize the backing store to 600 by 400.

Set the backing dimensions before drawing. Changing either one clears the canvas and resets its drawing state. If your draw calls use CSS coordinates, set the horizontal scale to the final backing width divided by the CSS width, and do the same for height. Then redraw the preview.

Drafted with AI. A local JavaScript test checked all three pixel calculations.

Want more #javascript & #images deep dives?

Join 5,999+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

More Posts

Cisco's Amy Chang: A Model's "Passport" Doesn't Tell You Where It Actually Came From

Tom Smithverified - Aug 27

Canvas cropping: keep source pixels separate from output size

jpgtosvg - Oct 17

Make for Small Business: What It Is, What It Costs, and When to Use It

floxolab - Oct 23

The Audit Trail of Things: Using Hashgraph as a Digital Caliper for Provenance

Ken W. Algerverified - Apr 28

Your canvas clicks are in the wrong coordinate system

remybyte - Oct 10
chevron_left
256 Points • 8 Badges
6Posts
0Comments
I work on Morphio, an online toolkit for HEIC conversion and image format workflows. I write about i... Show more

Related Jobs

Commenters (This Week)

4 comments
2 comments

Contribute meaningful comments to climb the leaderboard and earn badges!