1.2.0 • Published 1 year ago

pixel-perfect.js v1.2.0

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

pixel-perfect.js

Display images pixel-perfect

See example

Note:

It looks like image-resolution: snap CSS is supposed to do exactly what this library does. As if July 25th 2022 no browser has implemented it.

How to use

In your image tags that you want to be pixel perfect give them the class pixel-perfect and set a CSS size that is some integer multiple of your image.

Example:

<img src="100x150.png" class="pixel-perfect" style="width: 400px; height 600px">

Here we want the image displayed 4x it's original size. The reason to do it this way is so if the user has JavaScript disabled they'll still a size that matches your design.

Define your pixel-perfect class as follows

.pixel-perfect {
  image-rendering: pixelated;
  image-rendering: crisp-edges;
}

Include this script on your page

<script type="module" src="pixel-perfect.js"></script>;

Done!

Canvas

For <canvas> set both a width and height and a CSS width and height. Example:

<canvas width="200" height="100" class="pixel-perfect" style="width: 400px; height: 200px;"></canvas>

Note: as it says on the main page, this solution only works for designs that allow the canvas to change its display size relative to other elements. For example the canvas above is 200x100 pixels. To stay pixel perfect it can not go smaller, and going larger it must change to integer multiples like 400x200, 600x300, 800x400, etc...

If you have a canvas that fits a container or the entire page or that's required to have a fixed size then you need a different solution.

Special use cases

You can also import pixel-perfect.js as an es6 module.

import {makePixelPerfect} from './pixel-perfect.js';

You can then call makePixelPerfect on any <img> or <canvas> element.

For example:

import {makePixelPerfect} from './pixel-perfect.js';

function makeAllPixelPerfect() {
  document.querySelectorAll(".pixel-perfect").forEach(makePixelPerfect);
}
window.addEventListener('resize', makeAllPixelPerfect);
makeAllPixelPerfect();

License

MIT

1.2.0

1 year ago

1.1.2

2 years ago

1.1.1

2 years ago

1.1.0

2 years ago

1.0.1

2 years ago