Custom Drawings
Custom drawings add application-defined drawing types to DXcharts React. A definition supplies metadata, default properties, an AbstractFigure factory, and optional React UI for settings and toolbar shortcuts.
Example
The chart below registers a custom trend drawing and adds an instance after chart data is loaded.
The complete source for this example:
import React, { useCallback } from 'react';import type { ChartReactAPI } from '@dx-private/dxchart5-react/dist/chart/view-models/api/chart-react-api.view-model';import { ChartReactAppWrapper } from './ChartReactApp';const CUSTOM_TREND_ID = 'docs_custom_trend';const CUSTOM_TREND_INSTANCE_ID = 'docs_custom_trend_instance';export function CustomDrawingDemo() {const handleApiCreated = useCallback((api: ChartReactAPI): void => {const { Trend } = require('@dx-private/dxchart5-modules/dist/drawings/figures/Trend');api.registerCustomDrawings([{name: 'Custom trend',metainfo: {id: CUSTOM_TREND_ID,title: 'Custom trend',description: 'A custom drawing registered by the host application',icon: '<svg viewBox="0 0 16 16"><path d="M2 12 L6 5 L10 10 L14 3" stroke="currentColor" fill="none"/></svg>',defaultProperties: {drawingMode: 'both',drawingArea: { lineColor: '#2962ff', lineWidth: 1, lineDash: [], opacity: 0.15 },up: { lineColor: '#26a69a', lineWidth: 2, lineDash: [], opacity: 0.2 },down: { lineColor: '#ef5350', lineWidth: 2, lineDash: [], opacity: 0.2 },style: { fillBackground: true },},},constructor: () => new Trend(3),settingsTabs: ['general', 'coordinates'],},]);api.onChartCreated((chartId, chart) => {if (chartId !== '0') {return;}const candles = chart.chartModel.getCandles();if (candles.length < 3) {return;}const first = candles[Math.max(0, candles.length - 30)];const middle = candles[Math.max(1, candles.length - 15)];const last = candles[candles.length - 1];api.addDrawing({id: CUSTOM_TREND_INSTANCE_ID,type: CUSTOM_TREND_ID,synced: false,keyPoints: [{ timestamp: first.timestamp, value: first.close },{ timestamp: middle.timestamp, value: middle.close },{ timestamp: last.timestamp, value: last.close },],properties: {},visible: true,locked: false,isCustom: true,},chartId,);});}, []);return (<ChartReactAppWrapperheight={500}onApiCreated={handleApiCreated}uiOverrides={{ Logo: () => null }}width="100%"/>);}
Register a drawing type
Call registerCustomDrawings after the chart API is available. The definition ID must be unique; registering the same metainfo.id again replaces the previous definition.
export const registerPriceRangeDrawing = (api: ChartReactAPI,createFigure: () => AbstractFigure<unknown>,): void => {const definition: CustomDrawingDefinition<PriceRangeProperties> = {name: 'Price range',metainfo: {id: 'price_range',title: 'Price range',description: 'Shows a user-defined price range',icon: '<svg viewBox="0 0 16 16"><path d="M3 3v10M13 3v10M3 8h10"/></svg>',defaultProperties: {line: {lineColor: '#2962ff',lineWidth: 1,lineDash: [],},},},constructor: createFigure,settingsTabs: ['general', 'coordinates'],};api.registerCustomDrawings([definition]);}
The example receives createFigure separately. Your factory must return an implementation of AbstractFigure from the drawings module. The figure controls point count, canvas rendering, hit testing, dragging constraints, and cloning.
CustomDrawingDefinition
| Property | Type | Description |
|---|---|---|
name | string | Name shown in the drawings UI |
metainfo.id | string | Stable type identifier used by Drawing.type |
metainfo.title | string | Display title |
metainfo.shortTitle | string (optional) | Compact display title |
metainfo.description | string (optional) | Description shown to users |
metainfo.icon | ReactElement | string | Toolbar icon; strings normally contain SVG markup |
metainfo.defaultProperties | T | string | Default drawing properties or their JSON representation |
constructor | () => AbstractFigure | string | Figure factory or source text evaluating to a factory |
settingsTabs | ('general' | 'coordinates')[] (optional) | Built-in settings tabs to display |
SettingsComponent | ComponentType<CustomDrawingSettingsProps> (optional) | Additional settings content |
ToolbarShortcuts | ComponentType<CustomDrawingSettingsProps> (optional) | Controls shown in the selected-drawing toolbar |
Add and remove instances
Register the type before passing its ID to addDrawing. The id in this object identifies the drawing instance, while type refers to metainfo.id.
export const addPriceRange = (api: ChartReactAPI,fromTimestamp: number,toTimestamp: number,fromPrice: number,toPrice: number,): void => {api.addDrawing({id: 'price-range-1',type: 'price_range',synced: false,keyPoints: [{ timestamp: fromTimestamp, value: fromPrice },{ timestamp: toTimestamp, value: toPrice },],properties: {},visible: true,locked: false,});}
addDrawing(drawing, chartId?) adds a completed drawing. If chartId is omitted, DXcharts uses the selected chart and drawing synchronization settings. removeDrawing(instanceId) removes that instance from all charts.
To remove the type itself, call:
api.unregisterCustomDrawing('price_range');
Unregistering also removes every instance of that custom type from all charts.
Custom settings UI
SettingsComponent and ToolbarShortcuts receive CustomDrawingSettingsProps:
value— currentDrawingModel;onValueChange— reports the updated model;palette,drawingsDict,currentTimezone, andinstrument— current chart context;Reactandui— runtime dependencies available to serialized components.
The ui object exposes the same building blocks used by built-in drawing settings, including sections, groups, line controls, date-coordinate controls, checkboxes, and selectboxes.
export const PriceRangeSettings: React.FC<CustomDrawingSettingsProps> = ({value,onValueChange,ui,}
Assign the component when registering the definition:
api.registerCustomDrawings([
{
...definition,
SettingsComponent: PriceRangeSettings,
},
]);
Persist definitions
Provide customDrawingsProvider in ChartReactApp dependencies to load and save definitions. DXcharts calls the provider during initial loading and whenever an API registration changes the catalog.
export class BackendCustomDrawingsProvider implements CustomDrawingsProvider {public async getAllDrawings(): Promise<CustomDrawingDTO[]> {const response = await fetch('/api/chart/custom-drawings');return response.json();}public async getDrawing(id: string): Promise<CustomDrawingDTO | undefined> {const response = await fetch(`/api/chart/custom-drawings/${encodeURIComponent(id)}`);if (response.status === 404) {return undefined;}return response.json();}public async createDrawing(drawing: CustomDrawingDTO): Promise<void> {await this.save(drawing, 'POST');}public async updateDrawing(drawing: CustomDrawingDTO): Promise<void> {await this.save(drawing, 'PUT');}public async deleteDrawing(id: string): Promise<void> {await fetch(`/api/chart/custom-drawings/${encodeURIComponent(id)}`, {method: 'DELETE',});}private async save(drawing: CustomDrawingDTO, method: 'POST' | 'PUT'): Promise<void> {await fetch('/api/chart/custom-drawings', {method,headers: { 'Content-Type': 'application/json' },body: JSON.stringify(drawing),});}}
Pass the provider to the application:
export const customDrawingsDependencies = {customDrawingsProvider: new BackendCustomDrawingsProvider(),}
CustomDrawingsProvider
| Method | Purpose |
|---|---|
getAllDrawings() | Load all stored definitions during application initialization |
getDrawing(id) | Load one definition by metainfo.id |
createDrawing(dto) | Store a newly registered definition |
updateDrawing(dto) | Replace an existing definition |
deleteDrawing(id) | Delete an unregistered definition |
The provider stores CustomDrawingDTO, the serializable form of a definition. Icons, default properties, the figure factory, and optional React components are converted to strings. Functions restored from storage must be self-contained: imports, module variables, and closure values are not available when source text is evaluated.
Stored constructors and components are evaluated as JavaScript. Only load custom drawing definitions from a trusted, access-controlled source. Do not execute user-supplied code without separate validation and isolation.
API summary
| API | Purpose |
|---|---|
registerCustomDrawings(definitions) | Register and persist one or more drawing types |
unregisterCustomDrawing(typeId) | Remove a type and all of its instances |
addDrawing(drawing, chartId?) | Add a completed instance of a registered type |
removeDrawing(instanceId) | Remove an instance from all charts |