vprsdf
v1.0.7
Published
Tools for creating signed distance fields from image data
Downloads
27
Maintainers
Readme
VPR - SDF
vprsdf
is a fast and efficient signed distance field (SDF) generator designed for use in both Node.js and browser environments. It processes image pixel data as input and produces an array of corresponding distance values, which are normalized to a range of 0 to 255. This package operates without any external libraries, making it suitable for implementation in separate threads or web workers for asynchronous execution.
This package is a port of the beautifully explained algorithm from @tkmikyon.
Canvas Example
import { generateSdf } from "vprsdf";
import { loadImage } from "./utils";
(async () => {
// Get canvas and context
const canvas = document.querySelector("canvas") as HTMLCanvasElement;
const ctx = canvas.getContext("2d");
// Load an image
const image = await loadImage("/atom-small.png");
if (!ctx) return;
canvas.width = 400;
canvas.height = 400;
// Retrieve pixels from the image
ctx.drawImage(image, 0, 0, 400, 400);
const imageData = ctx.getImageData(0, 0, 400, 400);
// Compute signed distance field
const sdf = generateSdf(imageData.data, {
width: 400,
});
// Update image data with distances
for (let i = 0; i < sdf.length; i++) {
const distance = sdf[i];
imageData.data[i * 4] = distance;
imageData.data[i * 4 + 1] = distance;
imageData.data[i * 4 + 2] = distance;
imageData.data[i * 4 + 3] = 255;
}
ctx.putImageData(imageData, 0, 0);
})();