Skip to main content

Usage

Prerequisites#

First and foremost, Plaiceholder is a Node.js library. It's designed only to work in a Node.js environment.

Under-the-hood, it uses the wonderful and powerful sharp library to transform images.

Some frameworks or libraries include sharp by default, so double-check before you install.

npm i sharp

Installation#

npm i plaiceholder

Strategies#

CSS#

Converts a specified image into a low-res placeholder, outputted as a set of linear-gradients (in the form of a JavaScript style object).

For a "blurred" effect, extend the returned styles with filter: blur(<value>) and transform: scale(<value>).

Example#

import { getPlaiceholder } from "plaiceholder";
try {  getPlaiceholder("/path-to-your-image.jpg").then(({ css }) =>    console.log(css)  );} catch (err) {  err;}
// Logs// {//   backgroundImage: "…"//   backgroundPosition: "…"//   backgroundSize: "…"//   backgroundRepeat: "…"// }

SVG#

Converts a specified image into a low-res placeholder, outputted as an SVG.

For a "blurred" effect, extend the returned SVG's styles with filter: blur(<value>) and transform: scale(<value>).

note

Although it returns the SVG in the format of React.createElement() arguments, you are not constrained to using React.js.

e.g. See the 11ty example.

Example#

import { getPlaiceholder } from "plaiceholder";
try {  getPlaiceholder("/path-to-your-image.jpg").then(({ svg }) =>    console.log(svg)  );} catch (err) {  err;}
// Logs// [//   "svg",//   { ...svgProps }//   [//     [//       "rect",//       { ...rectProps }//     ],//     ...etc//   ]// ]

Base64#

Converts a specified image into a low-res image, encoded as Base64 string.

For a "blurred" effect, add filter: blur(<value>) and transform: scale(<value>) styles to the image.

Example#

import { getPlaiceholder } from "plaiceholder";
try {  getPlaiceholder("/path-to-your-image.jpg").then(({ base64 }) =>    console.log(base64)  );} catch (err) {  err;}
// Logs// data:image/jpeg;base64,/9j/2wBDAAYEBQY…

Blurhash#

Converts a specified image into a low-res image, encoded as Blurhash string accompanied by its width and height

This can be passed into a library such as react-blurhash.

Example#

import { getPlaiceholder } from "plaiceholder";
try {  getPlaiceholder("/path-to-your-image.jpg").then(({ blurhash }) =>    console.log(blurhash)  );} catch (err) {  err;}
// Logs//  {//    hash: "U.QSL{%1bdxtR...",//    height: 32,//    width: 32//  }

Helpers#

img#

Returns all essential <img /> attributes via the img object.

import { getPlaiceholder } from "plaiceholder";
try {  getPlaiceholder("/path-to-your-image.jpg").then(({ img }) =>    console.log(img)  );} catch (err) {  err;}
// Logs// {//   src: '…',//   width: …,//   height: …,//   type: '…'// }

Options#

getPlaiceholder("/path-to-your-image.jpg", {  // Any number value between 4-64  //   Default: 4  size: 4,});