README.md

June 19, 2026 ยท View on GitHub

ng-whiteboard

Lightweight angular whiteboard.

Build Status ng-whiteboard npm version License: MIT Downloads codecov

ng-whiteboard is a feature-rich, modular, and flexible whiteboard library for Angular. Designed for ease of use, performance, and a seamless drawing experience. It provides essential drawing tools and features with a scalable architecture.

๐Ÿ”— Live Demo

โœจ Features

  • ๐ŸŽจ SVG-based rendering for high-quality visuals
  • โšก Optimized performance for smooth interactions
  • ๐Ÿ“ฆ Modular, tree-shakable, and lightweight architecture
  • ๐Ÿ› ๏ธ Comprehensive Public API via WhiteboardService and component bindings
  • ๐Ÿ“ Undo/Redo, Zoom, Pan, and Save functionalities
  • ๐Ÿ–Š๏ธ Multiple drawing tools (pen, shapes, text, eraser, hand tool, etc.)
  • ๐Ÿ”„ Multi-instance support - Run multiple independent whiteboards simultaneously
  • โŒจ๏ธ Keyboard shortcuts - Full keyboard support for common operations
  • ๐Ÿ“‹ Context menu - Right-click menu for quick actions
  • ๐Ÿ“‘ Layer management - Control element z-index and stacking order
  • โœ‚๏ธ Copy/Paste/Cut - Full clipboard support for elements
  • ๐ŸŽฏ Selection tools - Select, move, resize, and rotate elements
  • ๐Ÿ”— Arrows - Arrows with customizable heads, and smart element binding
  • ๐Ÿ— Future-proof and scalable design

๐Ÿ“ฆ Installation

Install via yarn:

yarn add ng-whiteboard

or npm:

npm install ng-whiteboard

๐Ÿ”ง Integration

For Standalone Components

Import the component directly in your standalone component:

import { Component } from '@angular/core';
import { NgWhiteboardComponent } from 'ng-whiteboard';

@Component({
  selector: 'my-component',
  imports: [NgWhiteboardComponent],
  template: '<ng-whiteboard></ng-whiteboard>',
})
export class MyComponent {}

For NgModules

Import the component in your app.module.ts:

import { NgWhiteboardComponent } from 'ng-whiteboard';

@NgModule({
  imports: [NgWhiteboardComponent],
  // other imports
})
export class AppModule {}

๐Ÿš€ Usage

Basic Example

<ng-whiteboard></ng-whiteboard>

Advanced Example With Persist Data

import { Component, OnInit } from '@angular/core';
import { WhiteboardService } from 'ng-whiteboard';

@Component({
  selector: 'app-whiteboard-container',
  templateUrl: './whiteboard-container.component.html',
  styleUrls: ['./whiteboard-container.component.css'],
})
export class WhiteboardContainerComponent implements OnInit {
  whiteboardOptions: WhiteboardOptions = {
    backgroundColor: '#fff',
    strokeColor: '#2c80b1',
    strokeWidth: 5,
  };

  constructor(private whiteboardService: WhiteboardService) {}

  ngOnInit() {
    const savedData = localStorage.getItem('whiteboardData');
    if (savedData) {
      this.data = JSON.parse(savedData);
    }
  }

  onDataChange(data: WhiteboardElement[]) {
    localStorage.setItem('whiteboardData', JSON.stringify(data));
  }

  clearBoard() {
    this.whiteboardService.clear();
  }
}

Component Integration

<ng-whiteboard (dataChange)="onDataChange($event)" [options]="whiteboardOptions"></ng-whiteboard>

โš™๏ธ Configuration

InputTypeDefaultDescription
[data]WhiteboardElement[][]The whiteboard data
[options]WhiteboardOptionsnullComponent configuration object, properties described below
[drawingEnabled]booleantrueEnable mouse/touch interactions
[selectedTool]ToolTypeToolType.PenThe current selected tool
[canvasWidth]number800The width of whiteboard canvas
[canvasHeight]number600The height of whiteboard canvas
[fullScreen]booleantrueIf true, change (canvasWidth, canvasHeight) to fit the parent container
[strokeColor]string#333333The default stroke color
[backgroundColor]string#F8F9FAThe default background color
[fill]stringtransparentThe default fill color
[strokeWidth]number2The default stroke width
[zoom]number1Zoom level
[fontFamily]stringsans-serifThe default font family
[fontSize]number24The default font size
[center]booleantrueCenter the canvas in parent component, works with fullScreen: false
[x]number0If center is false, set the X axis
[y]number0If center is false, set the Y axis
[enableGrid]booleanfalseEnable the grid pattern
[gridSize]number10Set the grid inner boxes size
[snapToGrid]booleanfalseEnable snapping to grid
[lineJoin]LineJoinLineJoin.MiterThe default Line join
[lineCap]LineCapLineCap.ButtThe default Line cap
[dasharray]string''The default dash-array
[dashoffset]number0The default dash-offset
[arrowConfig]ArrowConfigSee belowArrow-specific configuration (heads, line style). See Arrow Configuration

๐Ÿน Arrow Configuration

The arrowConfig property controls the default appearance of newly drawn arrows.

import { ArrowConfig } from 'ng-whiteboard';

const config: Partial<WhiteboardConfig> = {
  arrowConfig: {
    startHeadStyle: 'none',
    endHeadStyle: 'open-arrow',
    lineStyle: 'curve',
  },
};
<ng-whiteboard [config]="config"></ng-whiteboard>

ArrowConfig Properties

PropertyTypeDefaultDescription
startHeadStyleArrowHeadStyle'none'Arrowhead style at the start of the arrow
endHeadStyleArrowHeadStyle'open-arrow'Arrowhead style at the end of the arrow
lineStyleArrowLineStyle'curve'Default path type for new arrows

ArrowHeadStyle Values

ValueDescription
'none'No arrowhead
'arrow'Filled triangle
'open-arrow'Open V-chevron (stroked)
'diamond'Filled diamond
'open-diamond'Open diamond outline
'circle'Filled circle
'open-circle'Open circle outline
'bar'Vertical bar (perpendicular line)

ArrowLineStyle Values

ValueDescription
'straight'Direct line between start and end points
'curve'Smooth quadratic curve with a draggable control point
'elbow'Right-angle (orthogonal) connector with a configurable bend position

Arrow Drawing Modifiers

ModifierBehavior
Shift + DragConstrains arrow angle to 15ยฐ increments
Drag near elementAuto-snaps to connection points (20px snap radius)

Smart Element Binding

Arrows can automatically bind to other elements (rectangles, ellipses, images, and text). When an arrow endpoint is dragged near a connectable element, it snaps to the nearest connection point and creates a binding. Bound arrows automatically update their position when the connected element is moved or resized.

Connection Points per Shape:

ShapeConnection Points
Rectangle8 points โ€” top, right, bottom, left, and 4 corners
Ellipse8 points โ€” cardinal directions and 45ยฐ positions on the ellipse
Image4 cardinal points (top, right, bottom, left)
Text4 cardinal points (top, right, bottom, left)

๐Ÿ“– API Reference

Important: Multi-Instance Support

ng-whiteboard supports multiple independent whiteboard instances. When using WhiteboardService, you must specify which board you're working with:

import { Component, AfterViewInit, inject } from '@angular/core';
import { NgWhiteboardService } from 'ng-whiteboard';

@Component({
  template: ` <ng-whiteboard [boardId]="boardId"></ng-whiteboard> `,
  providers: [NgWhiteboardService],
})
export class MyWhiteboardComponent implements AfterViewInit {
  private whiteboardService = inject(NgWhiteboardService);
  boardId = 'my-unique-board-id';

  ngAfterViewInit() {
    // IMPORTANT: Set the active board before using service methods
    this.whiteboardService.setActiveBoard(this.boardId);
  }

  clearBoard() {
    // Now this works on the correct board
    this.whiteboardService.clear();
  }
}

WhiteboardService Methods

๐Ÿ”€ Multi-Instance Management

  • setActiveBoard(boardId: string) Sets the specified board as active. All service operations will target this board.
  • activeBoard() Returns the ID of the currently active board, or null if no board is active.
  • clearActiveBoard() Clears the active board.
  • getAllBoards() Returns an array of all registered board IDs.
  • getBoardCount() Returns the total number of registered boards.
  • hasBoard(boardId: string) Checks if a board with the specified ID exists.

๐Ÿ“Š Reactive Signals (Active Board)

  • elements: Signal<WhiteboardElement[]> Returns elements from the active board.
  • elementsCount: Signal<number> Returns the number of elements on the active board.
  • hasElements: Signal<boolean> Returns true if the active board has any elements.

๐Ÿ“Œ Element Management

  • addElement(element: WhiteboardElement) Adds a new element (e.g., shape, text) to the whiteboard.
  • addImage(image: string, x?: number, y?: number) Adds an image to the whiteboard at a specified position.
  • removeElements(ids: string[]) Removes elements from the whiteboard by IDs.
  • updateElement(element: WhiteboardElement) Updates an existing element with new properties.
  • updateSelectedElements(partialElement: Partial<WhiteboardElement>) Modifies only specific properties of the currently selected element.
  • selectElements(elementsOrIds: WhiteboardElement | WhiteboardElement[] | string | string[]) Select element(s) on the whiteboard.
  • deselectElement(elementOrId: WhiteboardElement | string) Deselects a specific element on the whiteboard.
  • toggleSelection(elementOrId: WhiteboardElement | string) Toggle the selection of an element on the whiteboard.
  • selectAll() Selects all elements currently present on the whiteboard.
  • clearSelection() Clears any currently selected elements on the whiteboard.

๐Ÿ”„ State Management

  • clear() Clears all elements from the whiteboard.
  • undo() Reverts the last action.
  • redo() Restores the last undone action.
  • save(format = FormatType.Base64, name = 'New board') Saves the current whiteboard state in the specified format (e.g., Base64, JSON, SVG).

๐Ÿ–Œ Drawing Tools & Interaction

  • setActiveTool(tool: ToolType) Sets the current drawing tool (e.g., pen, eraser, shape).

๐ŸŽจ Canvas Control

  • setCanvasDimensions(width: number, height: number) Sets the width and height of the whiteboard canvas.
  • setCanvasPosition(x: number, y: number) Moves the canvas to a specific position.
  • centerCanvas() Centers the whiteboard canvas within the viewport.
  • fullScreen() Toggles full-screen mode for the whiteboard.
  • toggleGrid() Enables or disables the background grid for alignment.
  • dispatchBatch(actions: WhiteboardAction[]) Dispatches a batch of actions to the whiteboard.

๐Ÿ“‘ Layer Management

  • bringToFront(elementOrId: WhiteboardElement | string) Brings the specified element to the front (highest z-index).
  • bringForward(elementOrId: WhiteboardElement | string) Moves the element one layer forward.
  • sendToBack(elementOrId: WhiteboardElement | string) Sends the specified element to the back (lowest z-index).
  • sendBackward(elementOrId: WhiteboardElement | string) Moves the element one layer backward.
  • setZIndex(elementOrId: WhiteboardElement | string, zIndex: number) Sets the exact z-index for an element.
  • getZIndex(elementOrId: WhiteboardElement | string) Returns the current z-index of an element.

โœ‚๏ธ Clipboard Operations

  • copy() Copies the currently selected elements to the clipboard.
  • cut() Cuts the currently selected elements (copies and removes them).
  • paste() Pastes elements from the clipboard at the current cursor position.
  • duplicate() Duplicates the currently selected elements.

๐Ÿ” Viewport Control

  • zoomIn() Increases the zoom level.
  • zoomOut() Decreases the zoom level.
  • setZoom(level: number) Sets the zoom level to a specific value.
  • resetZoom() Resets the zoom level to 100%.
  • pan(deltaX: number, deltaY: number) Pans the canvas by the specified offset.
  • resetPan() Resets the canvas to its original position.

โŒจ๏ธ Keyboard Shortcuts

The whiteboard supports comprehensive keyboard shortcuts for enhanced productivity:

Selection & Editing

ShortcutAction
Ctrl/Cmd + ASelect all elements
EscapeClear selection
Delete / BackspaceDelete selected elements
Ctrl/Cmd + CCopy selected elements
Ctrl/Cmd + XCut selected elements
Ctrl/Cmd + VPaste elements
Ctrl/Cmd + DDuplicate selected elements

Undo/Redo

ShortcutAction
Ctrl/Cmd + ZUndo last action
Ctrl/Cmd + Shift + Z / Ctrl/Cmd + YRedo last undone action

Layer Management

ShortcutAction
Ctrl/Cmd + Shift + ]Bring to front
Ctrl/Cmd + ]Bring forward
Ctrl/Cmd + Shift + [Send to back
Ctrl/Cmd + [Send backward

Tools

ShortcutAction
VSelect tool
PPen tool
LLine tool
RRectangle tool
EEllipse tool
AArrow tool
TText tool
IImage tool
HHand tool (pan)
DEraser tool

Viewport

ShortcutAction
Ctrl/Cmd + + / Ctrl/Cmd + =Zoom in
Ctrl/Cmd + -Zoom out
Ctrl/Cmd + 0Reset zoom (100%)
Space + DragPan canvas (when not in hand tool mode)

Modifiers

ShortcutAction
Shift + DragConstrain proportions (drawing shapes)
Alt/Option + DragDraw from center (shapes)
Ctrl/Cmd + DragDuplicate while dragging

Note: Ctrl is used on Windows/Linux, Cmd (โŒ˜) is used on macOS.

๐Ÿ“‹ Context Menu

Right-click on the canvas or elements to access the context menu with quick actions:

Canvas Context Menu

  • Paste - Paste copied elements
  • Select All - Select all elements on canvas
  • Clear Canvas - Remove all elements

Element Context Menu

  • Cut - Cut selected element(s)
  • Copy - Copy selected element(s)
  • Paste - Paste from clipboard
  • Duplicate - Create a copy of selected element(s)
  • Delete - Remove selected element(s)
  • Bring to Front - Move to top layer
  • Bring Forward - Move one layer up
  • Send to Back - Move to bottom layer
  • Send Backward - Move one layer down

The context menu is context-aware and shows relevant options based on the current selection and clipboard state.

๐Ÿ“ข Whiteboard Events (Outputs)

The NgWhiteboardComponent emits the following events to notify about changes and interactions.

๐ŸŸข Lifecycle Events

  • ready Emitted when the whiteboard is fully initialized and ready for use.
  • destroyed Emitted when the whiteboard is destroyed, allowing for cleanup.

โœ๏ธ Drawing Events

  • drawStart Triggered when a user starts drawing on the whiteboard.
  • drawing Emitted continuously while the user is drawing.
  • drawEnd Triggered when the user stops drawing.

๐Ÿ”„ State & Data Events

  • undo Emitted when an undo action is performed.
  • redo Emitted when a redo action is performed.
  • clear Triggered when the whiteboard is cleared.
  • dataChange Emitted when the whiteboard's internal data state changes.
  • save Triggered when the whiteboard state is saved.

๐Ÿ“Œ Element Events

  • elementsAdded Emitted when a new element is added to the whiteboard.
  • elementsUpdated Triggered when an existing element is modified.
  • elementsSelected Emitted when an element is selected.
  • elementsDeleted Triggered when an element is removed.

๐Ÿ–ผ Image Events

  • imageAdded Emitted when an image is added to the whiteboard.

๐Ÿ›  Configuration & Tool Events

  • selectedToolChange Triggered when the active drawing tool is changed.
  • configChanged Emitted when the whiteboard configuration settings are updated.

๐Ÿค Contributing

We welcome contributions! Feel free to submit issues, feature requests, or pull requests.

๐Ÿ“œ License

This project is licensed under the MIT License.