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

declarative-canvas

v1.3.0

Published

Library which lets you draw on canvas in a declarative way.

Downloads

291

Readme

declarative-canvas

npm version

JavaScript/TypeScript library which lets you draw on HTML5 Canvas in a declarative way.

Installation

npm install declarative-canvas

Example Usage

The following code draws a rectangle and a circle on a canvas.

import { createDrawFunction, objectTypes } from 'declarative-canvas';

const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');

const draw = createDrawFunction();

const objectsToRender = [
  { type: objectTypes.RECT, x: 50, y: 100, width: 200, height: 100 },
  { type: objectTypes.CIRCLE, x: 200, y: 100, radius: 100 },
];

draw({ context, objects: objectsToRender });

Storybook

More examples can be found in the storybook. Source code of storybook stories is placed in the src/stories directory.

API Reference

declarative-canvas exports four objects/functions:

  • createDrawFunction - draw function factory,
  • objectTypes - dictionary object of available object types which can be drawn,
  • drawMethods - dictionary object of available drawing methods.
  • convertCanvasCoordinates - lets you convert canvas coordinates to base coordinates that you use to render objects.

createDrawFunction

A factory function that takes one optional argument:

(customDrawHandlers = {}) => Function;

customDrawHandlers argument is described in Custom draw handlers chapter.

A function returned from this factory has the following signature:

({
  context: CanvasRenderingContext2D,
  objects: Array<object>,
  canvasWidth = context.canvas && context.canvas.width,
  canvasHeight = context.canvas && context.canvas.width,
  camera = { position: { x: canvasWidth / 2, y: canvasHeight / 2 }, zoom: 1, rotation: 0 },
  clearCanvas = true,
}) => void

clearCanvas option clears canvas before rendering objects.

objectTypes

{
  CIRCLE: 'CIRCLE',
  PATH: 'PATH',
  IMAGE: 'IMAGE',
  TEXT: 'TEXT',
  RECT: 'RECT',
  TRANSFORM: 'TRANSFORM',
}

drawMethods

{
  FILL: 'FILL',
  STROKE: 'STROKE',
  FILL_AND_STROKE: 'FILL_AND_STROKE',
}

Draw method tells the renderer if the given graphical object should be drawn by filling it with some color or just by drawing its outline (or both).

convertCanvasCoordinates

(
  x: number,
  y: number,
  canvasWidth: number,
  canvasHeight: number,
  camera: Camera
) => { x: number, y: number }

A function that converts canvas coordinates (for example event.offsetX and event.offsetY from onclick event) to base coordinates that you use to render objects (taking into account any transformations caused by camera's position, rotation and zoom).

Available graphical objects

Rectangle

{
  type: objectTypes.RECT;
  contextProps?: Partial<CanvasRenderingContext2D>;
  drawMethod?: string;
  x: number;
  y: number;
  width: number;
  height: number;
  rotation?: number;
}

contextProps - Canvas context props. Default: {}
drawMethod - Draw method. Default: drawMethods.FILL
x - position of the center of rectangle in X axis
y - position of the center of rectangle in Y axis
width - rectangle width
height - rectangle height
rotation - rectangle rotation in radians. Default: 0

Circle

{
  type: objectTypes.CIRCLE;
  contextProps?: Partial<CanvasRenderingContext2D>;
  drawMethod?: string;
  x: number;
  y: number;
  radius: number;
}

contextProps - Canvas context props. Default: {}
drawMethod - Draw method. Default: drawMethods.FILL
x - position of the center of circle in X axis
y - position of the center of circle in Y axis
radius - circle radius

Path

{
  type: objectTypes.PATH;
  contextProps?: Partial<CanvasRenderingContext2D>;
  drawMethod?: string;
  points: Array<{ x: number; y: number }>,
  closePath?: boolean,
}

contextProps - Canvas context props. Default: {}
drawMethod - Draw method. Default: drawMethods.FILL
points - array of points that make the path
closePath - indicates if the last point should be connected to the first point. Default: false

Image

{
  type: objectTypes.IMAGE;
  contextProps?: Partial<CanvasRenderingContext2D>;
  image
  x: number;
  y: number;
  width?: number;
  height?: number;
  rotation?: number;
}

contextProps - Canvas context props. Default: {}
image - Image object
x - position of the center of image in X axis
y - position of the center of image in Y axis
width - image width. Defaults to image orginal width
height - image height. Defaults to image orginal height
rotation - image rotation in radians. Default: 0

Text

{
  type: objectTypes.TEXT;
  contextProps?: Partial<CanvasRenderingContext2D>;
  drawMethod?: string;
  text: string;
  x: number;
  y: number;
}

contextProps - Canvas context props. Default: {}
drawMethod - Draw method. Default: drawMethods.FILL
image - Image object
text - text to be rendered
x - position of the text in X axis. Text horizontal and vertical align can be adjusted by contextProps
y - position of the text in Y axis Text horizontal and vertical align can be adjusted by contextProps

Transform

{
  type: objectTypes.TRANSFORM;
  contextProps?: Partial<CanvasRenderingContext2D>;
  children: Array<GraphicalObject>;
  dx?: number;
  dy?: number;
  scaleX?: number;
  scaleY?: number;
  skewX?: number;
  skewY?: number;
  rotation?: number;
}

contextProps - Canvas context props. Default: {}
children - array of graphical objects
dx - displacement of child objects in X axis. Default: 0
dy - displacement of child objects in Y axis. Default: 0
scaleX - scaling of child objects in X axis. Default: 1
scaleY - scaling of child objects in Y axis. Default: 1
skewX - skew transformation applied to child objects in X axis. Default: 0
skewY - skew transformation applied to child objects in Y axis. Default: 0
rotation - rotation in radians of child objects. Default: 0

Context Props

For every graphical object you can specify contextProps property. Before drawing graphical object, all values of contextProps object will be assigned to Canvas Rendering Context. Some example values that you can use: fillStyle, strokeStyle, lineWidth, filter and so on. After drawing the graphical object, context properties will be restored back to their orginal values.

Custom draw handlers

If you want to expand the capabilities of declarative-canvas to support more object types, you can specify custom draw handlers which will be used to draw objects with specified object type. Draw handler is a function with the following signature:

(context, options, drawObject) => void

To see examples of draw handlers, you can check out default draw handlers in src/drawHandlerFunctions directory.

Custom handlers can be passed as a customDrawHandlers argument to createDrawFunction. customDrawHandlers should be an object, where keys represent object types and values represent custom handlers.