npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

webgl-sdf-generator

v1.1.1

Published

WebGL-accelerated signed distance field generation for 2D paths

Downloads

999,108

Readme

webgl-sdf-generator

This is a signed distance field (SDF) image generator for 2D paths such as font glyphs, for use in Web environments. It utilizes WebGL when possible for GPU-accelerated SDF generation.

Usage

Install it from npm:

npm install webgl-sdf-generator

NPM

Import and initialize:

import initSDFGenerator from 'webgl-sdf-generator'
// or: const initSDFGenerator = require('webgl-sdf-generator')

const generator = initSDFGenerator()

The webgl-sdf-generator package's only export is a factory function which you must invoke to return an object which holds various methods for performing the generation.

Why a factory function? The main reason is to ensure the entire module's code is wrapped within a single self-contained function with no closure dependencies. This enables that function to be stringified and passed into a web worker, for example.

Note that each factory call will result in its own internal WebGL context, which may be useful in some rare cases, but usually you'll just want to call it once and share that single generator object.

Generate a single SDF:

const sdfImageData = generator.generate(
  64,                  // width
  64,                  // height
  'M0,0L50,25L25,50Z', // path 
  [-5, -5, 55, 55],    // viewBox
  25,                  // maxDistance
  1                    // exponent
)

Let's break down those arguments...

  • width/height - The dimensions of the resulting image.

  • path - An SVG-like path string. Only the following path commands are currently supported: M, L, Q, C, and Z.

  • viewBox - The rectangle in the path's coordinate system that will be covered by the output image. Specified as an array of [left, top, right, bottom]. You'll want to account for padding around the path shape in this rectangle.

  • maxDistance - The maximum distance that will be encoded in the distance field; this is the distance from the path's edge at which the SDF value will be 0 or 255.

  • exponent - An optional exponent to apply to the SDF distance values as they get farther from the path's edge. This can be useful when maxDistance is large, to allow more precision near the path edge where it's more important and decreasing precision far away (visualized here). Whatever uses the SDF later on will need to invert the transformation to get useful distance values. Defaults to 1 for no curve.

The return value is a Uint8Array of SDF image pixel values (single channel), where 127.5 is the "zero distance" aligning with path edges. Values below that are outside the path and values above it are inside the path.

When you call generator.generate(...), it will first attempt to build the SDF using WebGL; this is super fast because it is GPU-acclerated. This should work in most browsers, but if for whatever reason the proper WebGL support is not available or fails due to context loss then it will fall back to a slower JavaScript-based implementation.

If you want more control over this fallback behavior, you can access the individual implementations directly:

// Same arguments as the main generate():
const resultFromGL = generator.webgl.generate(...args)
const resultFromJS = generator.javascript.generate(...args)

The WebGL implementation also provides method to detect support if you want to test it beforehand:

const webglSupported = generator.webgl.isSupported()

Generate an atlas of many SDFs:

Making a single SDF has its uses, but it's likely that you actually want that SDF to be added to a larger "atlas" image of many SDFs. While you could do that by calling generator.generate() as above and manually inserting the returned Uint8Array into a larger texture, that isn't optimal because it involves reading pixels back from the GPU for every SDF, which has a performance impact.

Instead, you can generate an SDF directly into a region+channel of a WebGL-enabled canvas, populating your "atlas" directly on the GPU. Only the region/channel for the new SDF will be overwritten, the rest will be preserved. That canvas can then be used as the source for a WebGL texture for rendering. This ends up being much faster since the data all stays on the GPU.

generator.generateIntoCanvas(
  64,                  // width
  64,                  // height
  'M0,0L50,25L25,50Z', // path 
  [-5, -5, 55, 55],    // viewBox
  25,                  // maxDistance
  1,                   // exponent
  yourCanvasElement,   // output canvas
  128,                 // output x coordinate
  64,                  // output y coordinate
  0                    // output color channel              
)

And similarly for the individual implementations:

// Same arguments as the main generate():
generator.webgl.generateIntoCanvas(...args)
generator.javascript.generateIntoCanvas(...args)

Note that the canvas you pass:

  • must be WebGL-enabled, meaning that getContext('webgl') will succeed for it; you can't give it a canvas with a 2d context, for example.
  • should not be shared with other processes that change the GL context state; generateIntoCanvas only sets the exact state it needs and makes no attempt to restore previous state, so sharing it could lead to unpredictable results.