Skip to main content

Your First Editor

Get a working Canvas Editor instance up and running in just a few minutes. This guide walks you through creating a basic editor with text formatting capabilities.
1

Set up your HTML

Create a container element for the editor. The container needs explicit dimensions:
index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Canvas Editor</title>
  </head>
  <body>
    <div class="canvas-editor"></div>
  </body>
</html>
Canvas Editor requires a container with defined width and height. Use CSS or inline styles to set dimensions.
2

Install the package

Install Canvas Editor using your preferred package manager:
npm install @hufe921/canvas-editor
3

Create your editor instance

Import the Editor class and initialize it with content:
main.ts
import Editor from '@hufe921/canvas-editor'

// Get the container element
const container = document.querySelector('.canvas-editor')

// Create editor instance
const editor = new Editor(container, {
  main: [
    {
      value: 'Hello World'
    }
  ]
})
The editor will render immediately with the provided content.
4

Try it out

Open your application in a browser. You should see an editable text editor with “Hello World”. Click to start typing and editing!

Complete Working Example

Here’s a complete example with TypeScript, including header, main content, and footer sections:
main.ts
import Editor, { 
  IEditorData, 
  IEditorOption,
  RowFlex,
  ElementType 
} from '@hufe921/canvas-editor'

// Define your document structure
const data: IEditorData = {
  header: [
    {
      value: 'Document Header',
      size: 24,
      bold: true,
      rowFlex: RowFlex.CENTER
    },
    {
      value: '\n',
      type: ElementType.SEPARATOR
    }
  ],
  main: [
    {
      value: 'Welcome to Canvas Editor! ',
      size: 18,
      bold: true
    },
    {
      value: 'This is a powerful rich text editor built with TypeScript.\n\n'
    },
    {
      value: 'Features include:'
    },
    {
      value: '\n• Rich text formatting'
    },
    {
      value: '\n• Table support'
    },
    {
      value: '\n• Image handling'
    },
    {
      value: '\n• Print and export'
    }
  ],
  footer: [
    {
      value: 'Page ',
      size: 12,
      color: '#666666'
    }
  ]
}

// Configure editor options
const options: IEditorOption = {
  defaultFont: 'Arial',
  defaultSize: 16,
  defaultColor: '#000000',
  margins: {
    top: 100,
    right: 120,
    bottom: 100,
    left: 120
  }
}

// Initialize editor
const container = document.querySelector<HTMLDivElement>('.canvas-editor')!
const editor = new Editor(container, data, options)

// Access the command API
console.log('Editor instance created:', editor)
console.log('Version:', editor.version)
The header and footer sections are optional. You can also pass just an array of elements as the second parameter, which will be treated as the main content.

Using Commands

The Command API allows you to programmatically manipulate the editor content:
import Editor from '@hufe921/canvas-editor'

const editor = new Editor(
  document.querySelector('.canvas-editor'),
  { main: [{ value: 'Hello World' }] }
)

// Access command methods
const { command } = editor

// Format text
command.executeBold()        // Toggle bold
command.executeItalic()      // Toggle italic
command.executeUnderline()   // Toggle underline

// Change font and size
command.executeFont('Times New Roman')
command.executeSize(18)
command.executeColor('#FF0000')

// Insert elements
command.executeInsertTable(3, 4)  // 3 rows, 4 columns
command.executePageBreak()

// Undo/Redo
command.executeUndo()
command.executeRedo()

// Get editor content
const value = command.getValue()
console.log('Current content:', value)
All command methods follow the naming pattern execute*. Explore the full Command API reference for available operations.

Listening to Events

React to editor changes using the Listener API:
import Editor from '@hufe921/canvas-editor'

const editor = new Editor(
  document.querySelector('.canvas-editor'),
  { main: [{ value: 'Hello World' }] }
)

// Listen to range style changes
editor.listener.rangeStyleChange = (payload) => {
  console.log('Selection changed:', payload)
  console.log('Is bold?', payload.bold)
  console.log('Font:', payload.font)
  console.log('Size:', payload.size)
}

// Listen to content changes
editor.listener.contentChange = () => {
  console.log('Content was modified')
  const value = editor.command.getValue()
  // Save to backend, localStorage, etc.
}

// Listen to control value changes
editor.listener.controlChange = (payload) => {
  console.log('Control changed:', payload)
}

Practical Examples

Implement automatic saving with debouncing:
import Editor from '@hufe921/canvas-editor'

const editor = new Editor(
  document.querySelector('.canvas-editor'),
  { main: [{ value: 'Start typing...' }] }
)

// Debounce helper
function debounce(func: Function, wait: number) {
  let timeout: NodeJS.Timeout
  return (...args: any[]) => {
    clearTimeout(timeout)
    timeout = setTimeout(() => func(...args), wait)
  }
}

// Auto-save on content change
const autoSave = debounce(() => {
  const data = editor.command.getValue()
  localStorage.setItem('editor-content', JSON.stringify(data))
  console.log('Content saved!')
}, 1000)

editor.listener.contentChange = autoSave

// Load saved content on startup
const saved = localStorage.getItem('editor-content')
if (saved) {
  editor.command.setValue(JSON.parse(saved))
}

Next Steps

Now that you have a working editor, explore more features:

Configuration Guide

Learn about all available configuration options

Text Formatting

Explore rich text formatting capabilities

Working with Tables

Insert and manipulate tables in your documents

Command API

Master the complete Command API
Remember to properly destroy editor instances when unmounting components to prevent memory leaks:
// When you're done with the editor
editor.destroy()

Build docs developers (and LLMs) love