Categories: CSSScriptWeb Design

Declarative Canvas Drawing in JavaScript – DrawableJS

DrawableJS is a lightweight JavaScript library that transforms HTML5 canvas elements into powerful drawing surfaces for shapes, gradients, text, and images.

It provides a declarative way to define what you want on the canvas, rather than writing a ton of imperative `ctx.moveTo`, `ctx.lineTo`, `ctx.arc` calls for every visual element.

Table of Contents

Toggle

Features:

  • Basic shape rendering – rectangles, ovals, lines and images with minimal code
  • Advanced styling options – solid colors, linear/radial gradients, borders, rounded corners and shadows
  • Text rendering – with font selection, sizing and alignment controls
  • Extensible architecture – shapes can include custom content and post-draw functions
  • Module support – works with ES Modules and UMD (classic script tags)
  • Efficient updates – optimized for animations and dynamic content

How to use it:

1. Install DrawableJS and import modules:

# NPM
$ npm install drawable-js
import { Drawable, Shape, Gradient } from 'drawable-js';

2. Or include the UMD version directly in your HTML:

<script src="/dist/drawable.umd.js"></script>

3. Get canvas context.

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

4. Create a Drawable instance with dimensions:

const rect = new Drawable(200, 100);
rect.ctx = ctx;

5. Define an update function containing drawing instructions.

rect.update = () => {
  rect.items = [
  {
    shape: Shape.RECTANGLE,
    x: 20,
    y: 20,
    width: 200,
    height: 100,
    gradient: {
      type: Gradient.LINEAR_GRADIENT,
      angle: 45, 
      center: { x: '50%', y: '50%' },
      startColor: "#FF5733",
      endColor: "#FFC300"
    },
    stroke: {
      color: "#333333",
      width: 2
    },
    cornerRadius: [15, 15, 15, 15]  // Rounded corners
  }
  ];
};

6. Call build() to draw a rectangle with a linear gradient:

rect.build();

7. All item object properties:

  • shape: Shape.RECTANGLE, Shape.OVAL, Shape.LINE.
  • Coordinates & Dimensions: x, y, width, height, radius (for ovals). For lines: from: {x, y}, to: {x, y}.
  • color: A string for solid fill color (e.g., "#FF0000").
  • gradient: An object describing a gradient.
    • type: Gradient.LINEAR_GRADIENT or Gradient.RADIAL_GRADIENT.
    • Linear: angle, center (object {x: 'percentage', y: 'percentage'}), startColor, endColor, centerColor (optional).
    • Radial: center1 (object {x, y}), radius1, center2 (object {x, y}), radius2, startColor, endColor, centerColor (optional).
  • stroke: An object { color: "hexOrRgba", width: number }.
  • cornerRadius: An array of 4 numbers: [topLeft, topRight, bottomRight, bottomLeft].
  • shadow: An object { dx: number, dy: number, color: "hexOrRgba", blur: number }.
  • text: The string to display.
  • font: A Font enum value (e.g., Font.ARIAL). These enums include hPerc and lowerOverlap values for better text metric calculations.
  • size: Font size in pixels.
  • textAlign: Canvas textAlign values (left, center, right).
  • vAlign: Vertical alignment (top, middle, bottom). The library uses font.hPerc and font.lowerOverlap to try and position these more accurately.
  • image: Can be an image URL string (like 'image/url') or image data.
  • url: If image is 'image/url', this is the path to the image.
  • colorFilter: A color string to tint an image.

8. API methods.

  • ctx: Your canvas 2D context.
  • items: An array. Each element is an object defining something to draw.
  • update(): A function you define. It should populate the this.items array. Called by build().
  • build(msInterval): Renders the items. If msInterval is provided and newState() is defined, it sets up a setInterval animation. Otherwise, if newState() is defined, it uses requestAnimationFrame. If newState() isn’t defined, it’s a static draw.
  • clear(): Clears the area defined by the Drawable‘s x, y, width, height.
  • onFirstBuild, onPostBuild: Optional callback hooks.
  • newState(): Optional function for animations. Return true to continue animating, false to stop.

The post Declarative Canvas Drawing in JavaScript – DrawableJS appeared first on CSS Script.

rssfeeds-admin

Share
Published by
rssfeeds-admin

Recent Posts

Flawed Victory: The Long Road to a Good Mortal Kombat Movie Sequel

Since its release in 1997, Mortal Kombat: Annihilation’s place in the annals of video game…

2 minutes ago

Grown Ups 3 Is Officially in the Works at Netflix With Adam Sandler Returning

Netflix has confirmed that it is developing Grown Ups 3 with Adam Sandler, over a…

2 minutes ago

Netflix to Adapt Vault Comics’ Fantasy Series Barbaric

Netflix has another big-budget comic book adaptation in the works, with the streamer giving a…

2 minutes ago

Sen. Todd Young – US Ship Building

WASHINGTON, (WOWO) — U.S. Sen. Todd Young (R-Ind.) is part of a group of senators…

32 minutes ago

Indiana Governor Mike Braun And Cell Phone Ban In Schools

INDIANAPOLIS, Ind. (WOWO) — Indiana Governor Mike Braun signed Senate Enrolled Act 78 on Wednesday,…

32 minutes ago

Trump taps former career ICE official to lead agency

An Immigration and Customs Enforcement ICE officer's badge and weapon are seen in Washington, D.C.,…

36 minutes ago

This website uses cookies.