How to archieve pixel-perfect pixelart upscaling with css?

683 Views Asked by At

I want to upscale my pixelart sprite with css and have it look crisp. But I have 3 issues with pixelart and css:

  1. Upscaling is blurry by default (has been solved many times already)
  2. CSS px is not the size of a screen's pixel (can't be solved apparently)
  3. I can't find a way to upscale my img by an integer factor so pixels stay perfect squares (what I struggle to do)

One of my failed attemps

1

There are 1 best solutions below

0
selm On

Since you need to upscale your picture by an integer factor in order for the pixels to stay squares, and since CSS doesn't give you the "true size of 1 pixel" you have to run your own calculations, depending on the end user's viewport pixel width.

Here is an example:

.pixel-perfect {
  image-rendering: crisp-edges; /*no blur*/

  /*pixel-perfect upscaling of a 15px wide image on a 1920px wide viewport by a factor of 4x */
  width: calc(calc(100vw / calc(1920 /*viewport screen pixel width, needs to be equivalent to 100vw for it to look best*/ / 4 /*factor*/)) * 15 /*pixelart width*/) 
}
<html>
  <body>
    <img class="pixel-perfect" src="https://imgur.com/3gtdA0P.png"/>
  </body>
</html>