Declarativas API

Declarativas exposes three simple methods to get you going.

Methods

Mutating the Canvas Context 2d Api

import { createMutator } from 'declarativas';

createMutator(ctx => ctx.fillRect(1, 1, 10, 10));

createMutator(ctx => {
  ctx.fillStyle = 'green';
});

The createMutator(fn) method is a way to directly manipulate the canvas state. This is the building block to creating components.

Building Components

/**
 * @jsx createElement
 */
import { createMutator, createElement } from 'declarativas';

const FillText = (props, children, context2d) => {
  return [
    createMutator((ctx) => { ctx.fillStyle = props.color; }),
    createMutator((ctx) => ctx.fillText(props.text, props.x, props.y)),
  ];
}

// And to use the component:

createElement(FillText, { color: 'black', text: 'foo', x: 10, y: 10 });

// OR

<FillText color='black' text='foo' x={10} y={10} />

Render components to the canvas

import { render, createElement as c, Properties } from 'declarativas';

render(
  [
    c(Properties, { fillStyle: 'black' }),
    c(FillText, { color: 'black', text: 'Hello world', x: 1, y: 1 }),
  ],
  document.querySelector('canvas').getContext('2d'),
);

Calling the render method will draw whatever virtual canvas nodes you have created onto the canvas you specified. If you want to update the canvas, just call render again. There is no extra state/updating mechanism built in, but there is nothing stopping any developer from integrating declarativas into a state management library.

Built-in Components

  • DrawImage

  • FillRect/StrokeRect

  • Path - uses the beginPath, path elements, fill, and stroke to build a path

    • MoveTo

    • LineTo

    • Rect

    • RoundRect

    • Arc/ArcTo

    • CurveTo - bezier or quadratic curves

    • Ellipse

    • Text

  • ClearRect - clear portion of screen

  • ClearCanvas - clear entire canvas

  • Translate

  • Rotate

  • Scale

  • Transform

  • Stateful - wraps drawing in a save/restore for color and transform states

  • Property - write a single property to the context2d

  • Properties - write multiple properties to the context2d

  • ErrorBoundary - catch errors and render an error message

  • Group - work-around for JSX so you can have multiple "root" elements

Last updated