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 🙏

© 2025 – Pkg Stats / Ryan Hefner

canvcass

v1.0.0

Published

High-level Napi-RS Canvas Wrapper for flexibility and productivity.

Readme

CanvCass — Full API Documentation (Premium Edition)

A high-level napi-rs canvas wrapper with streamlined drawing utilities, smart layout helpers, text breaking, gradients, clipping, image tools, and more.

Everything is organized progressively so absolute beginners can learn without drowning, while experts can find everything quickly.


TABLE OF CONTENTS

  1. Introduction
  2. Creating a Canvas
  3. Canvas Geometry & Config
  4. Rect Tools
  5. Context, Blending & Export
  6. Drawing Shapes
  7. Text Rendering
  8. Images
  9. Gradients
  10. Paths
  11. Clipping
  12. Layout (Flexbox-like)
  13. Measurements & Text Utilities
  14. Fonts
  15. Loading Images
  16. All Types & Interfaces

Introduction

CanvCass is a high-level drawing layer built on top of @napi-rs/canvas, giving you:

✅ Easier drawing APIs ✅ Layout-aware rectangles ✅ Smart text rendering with auto line breaks ✅ Clean image loading & drawing ✅ Gradients (straight, dim, angled) ✅ Path helpers ✅ Blend modes ✅ Flexbox-like layout ✅ Clipping helpers

This documentation teaches you from the ground up, starting with the simplest operations and building toward advanced drawing.


Creating a Canvas


Constructor Overload 1 — Fixed Size

constructor(width: number, height: number)

✅ Explanation

Creates a new canvas with the given width and height.

✅ Example

const canvas = new CanvCass(800, 600);

Constructor Overload 2 — With Background Config

constructor(config: CanvCass.CreateConfig)

✅ Explanation

Creates a canvas with width, height, and optional background.

✅ Example

const canvas = new CanvCass({
  width: 800,
  height: 600,
  background: '#1a1a1a'
});

Premade Canvas

static premade(): CanvCass

✅ Explanation

Creates a default-sized canvas using internal static preW and preH.

✅ Example

const canvas = CanvCass.premade();

Change Resolution / Scale

changeScale(size: number): void

✅ Explanation

Scales the internal canvas resolution. Useful for higher DPI exports; increases memory.

✅ Example

canvas.changeScale(2); // high resolution

Reset Canvas

reset(): void

✅ Explanation

Resets canvas width, height, and transform matrix to defaults.

✅ Example

canvas.reset();

Canvas Geometry & Config

Every property below is read-only.


Canvas Config

readonly config: CanvCass.CreateConfig

✅ Explanation

The configuration object passed during construction.


Width / Height

readonly width: number
readonly height: number
readonly realWidth: number
readonly realHeight: number

✅ Explanation

  • width/height = intended logical size
  • realWidth/realHeight = scaled size

✅ Example

console.log(canvas.width, canvas.realWidth);

Canvas Edges

readonly left: number      // always 0
readonly top: number       // always 0
readonly right: number     // == width
readonly bottom: number    // == height

✅ Example

console.log(canvas.right, canvas.bottom);

Canvas Center

readonly centerX: number   // width / 2
readonly centerY: number   // height / 2

✅ Example

console.log(canvas.centerX, canvas.centerY);

Canvas Rect

readonly rect: CanvCass.Rect

✅ Explanation

Returns a full rect representing the entire canvas.

✅ Example

const full = canvas.rect;
console.log(full.centerX);

Rect Tools


Create Rect

static createRect(basis: Partial<CanvCass.MakeRectParam>): CanvCass.Rect

✅ Explanation

Builds a complete rect even with partial input (auto-completes right/center/etc.)

✅ Example

const rect = CanvCass.createRect({ width: 200, height: 100, left: 50 });

Context, Blending & Export


Set Blend Mode

setBlendMode(op: SKRSContext2D["globalCompositeOperation"]): void

✅ Example

canvas.setBlendMode('multiply');

Reset Blend Mode

resetBlendMode(): void

Temporary Context Access

withContext(cb: (ctx: SKRSContext2D) => void): void

✅ Explanation

Automatically saves/restores state. ⚠️ DO NOT call save() or restore() inside the callback.

✅ Example

canvas.withContext(ctx => {
  ctx.fillStyle = 'red';
  ctx.fillRect(0, 0, 100, 100);
});

Export to PNG

toPng(): Buffer<ArrayBufferLike>

✅ Example

require('fs').writeFileSync('output.png', canvas.toPng());

Export to Stream

toStream(): Promise<ReadStream>

✅ Example

const stream = await canvas.toStream();
stream.pipe(fs.createWriteStream('output.png'));

Drawing Shapes


drawBackground

drawBackground(): Promise<void>

✅ Example

await canvas.drawBackground();

drawBox (Multiple Overloads)

Overload 1 — Rect Object

drawBox(style?: { rect: CanvCass.Rect } & Partial<CanvCass.DrawBoxInlineParam>): void

Overload 2 — Inline Rect Creation

drawBox(style: CanvCass.DrawBoxInlineParam): void

Overload 3 — "Legacy" Format

drawBox(left: number, top: number, width: number, height: number, style?: Partial<CanvCass.DrawBoxInlineParam>): void

✅ Explanation

Draw rectangles with optional fill, stroke, and corner radius.

✅ Example

canvas.drawBox({
  left: 50, top: 50, width: 200, height: 120,
  fill: 'purple', stroke: 'white', strokeWidth: 3
});

drawPolygon

drawPolygon(points: number[][], style?: CanvCass.DrawParam): void

✅ Example

canvas.drawPolygon(
  [[0,0],[100,50],[50,100]],
  { fill: 'lime', stroke: 'black', strokeWidth: 2 }
);

drawLine

drawLine(start: [number, number], end: [number, number], style?: CanvCass.DrawParam): void
drawLine(points: [number, number][], style?: CanvCass.DrawParam): void

✅ Example

canvas.drawLine([10,10], [200,80], { stroke: 'red', strokeWidth: 4 });

drawFromPath

drawFromPath(
  path: Path2D,
  style?: { fill?: CanvCass.Color; stroke?: CanvCass.Color; strokeWidth?: number }
): void

✅ Example

const path = new Path2D();
path.rect(50, 50, 200, 100);
canvas.drawFromPath(path, { fill: 'cyan' });

drawCircle

drawCircle(center: [number, number], radius: number, style?: CanvCass.DrawCircleParamN): void
drawCircle(config: CanvCass.DrawCircleParam): void

✅ Example

canvas.drawCircle([150,150], 80, { fill: 'gold', stroke: 'black', strokeWidth: 4 });

Text Rendering

This section is HUGE — and fully complete.


setFont

setFont(family: string): void

✅ Example

canvas.setFont('Arial');

resetFont

resetFont(): void

✅ Example

canvas.resetFont();

drawText (3 Overloads)

drawText(text: string, x: number, y: number, options?: Partial<CanvCass.DrawTextParam>): CanvCass.DrawTextResult
drawText(text: string, options: Partial<CanvCass.DrawTextParam>): CanvCass.DrawTextResult
drawText(config: CanvCass.DrawTextParam): CanvCass.DrawTextResult

✅ Explanation

Draws text with:

  • Auto line wrapping
  • Alignment
  • Vertical alignment
  • Stroke
  • Letter spacing
  • Line height
  • Direction control
  • Font type presets

✅ Simple Example

canvas.drawText("Hello World", 100, 80, {
  size: 32,
  fill: 'white',
  align: 'center'
});

✅ Multiline Example

canvas.drawText({
  text: "This text wraps automatically.",
  x: 50,
  y: 100,
  breakMaxWidth: 200,
  fill: 'white'
});

Images

✅ drawImage (overloads)

drawImage(image: Image, left: number, top: number, options?: CanvCass.DrawImageConfig): Promise<void>
drawImage(src: string | Buffer, left: number, top: number, options?: CanvCass.DrawImageConfig): Promise<void>

✅ Explanation

Draw images from file paths, buffers, or napi-rs Image objects. Supports cropping, resizing, and clip masks.

✅ Example

await canvas.drawImage('photo.jpg', 0, 0, { width: 300 });

Gradients


createDim

createDim(
  rect: CanvCass.Rect,
  options?: { fadeStart?: number; fadeEnd?: number; color?: string }
): CanvasGradient

✅ Example

const dim = canvas.createDim(canvas.rect, { color: 'black', fadeEnd: 0.8 });

defaultGradient

defaultGradient(width: number, height: number): CanvasGradient

✅ Example

ctx.fillStyle = canvas.defaultGradient(800, 600);

tiltedGradient

tiltedGradient(
  width: number,
  height: number,
  angleRad: number,
  colorStops: [number, string][]
): CanvasGradient

✅ Example

const grad = canvas.tiltedGradient(400, 400, Math.PI/3, [
  [0, 'red'],
  [1, 'blue']
]);

Paths


✅ rectToPath

static rectToPath(rect: CanvCass.Rect): Path2D

✅ Example

const path = CanvCass.rectToPath(rect);

✅ createCirclePath

static createCirclePath(center: [number, number], radius: number): Path2D

✅ createCorneredRectPath

static createCorneredRectPath(radius: number, rect: CanvCass.Rect): Path2D

Clipping


✅ withClip

withClip(path: Path2D, cb: () => void): void

✅ withClipAsync

withClipAsync(path: Path2D, cb: () => Promise<void>): Promise<void>

Layout (Flexbox-like)


✅ drawFlexbox

drawFlexbox(
  container: {
    rect: CanvCass.Rect;
    flexDirection?: "row" | "column";
    justifyContent?: "flex-start" | "center" | "flex-end" | "space-between" | "space-around";
    alignItems?: "flex-start" | "center" | "flex-end" | "stretch";
    gap?: number;
  },
  children: Array<
    (Partial<CanvCass.MakeRectParam> & { fill?: CanvCass.Color }) |
    ((rect: CanvCass.Rect, index: number) => void)
  >
): void

✅ Example

canvas.drawFlexbox(
  { rect: canvas.rect, flexDirection: 'row', gap: 10 },
  [
    { width: 100, height: 100, fill: 'red' },
    { width: 100, height: 100, fill: 'blue' }
  ]
);

Measurements & Text Utilities


✅ measureText

measureText(style: CanvCass.MeasureTextParam): _napi_rs_canvas.TextMetrics

✅ splitBreak

splitBreak(style: CanvCass.MeasureTextParam, maxW: number): string[]

✅ splitBreakDetailed

splitBreakDetailed(
  style: CanvCass.MeasureTextParam,
  maxW: number
): { lines: string[]; maxWidth: number }

✅ splitBreakOld

splitBreakOld(style: CanvCass.MeasureTextParam, maxW: number): string[]

✅ lineYs

static lineYs(height: number, lines: number, offset?: number): number[]

Fonts


✅ registerFont

static registerFont(font: CanvCass.Font): void

✅ Example

CanvCass.registerFont({
  name: 'Roboto',
  path: './fonts/Roboto.ttf'
});

✅ Global Fonts

static fonts: _napi_rs_canvas.IGlobalFonts

Loading Images


✅ loadImage

function loadImage(
  source: string | URL | Buffer | ArrayBufferLike | Uint8Array | Image | stream.Readable,
  options?: LoadImageOptions
): Promise<Image | undefined>

✅ Example

const img = await CanvCass.loadImage('photo.png');

Credits

CanvCass was created and maintained by Liane Cagara.

Special thanks to:

  • @napi-rs/canvas — for providing the high-performance Node.js canvas foundation.
  • Node.js — for powering the runtime environment.
  • TypeScript — for enabling precise type safety and developer-friendly APIs.
  • Open Source Contributors — whose libraries, ideas, and inspiration made this project possible.

Inspired by the simplicity of browser Canvas APIs and the power of server-side rendering.