- Fixed doRedo being a private method
- Added experimental eraser functionality:
eraserLineWidth?: number;
eraseButtonEnabled?: boolean;
eraseButtonClass?: string;
eraseButtonText?: string;
This allows for implementing a dragging mechanism
- Updated to Angular 12
- Added TypeScript strict mode
- Added the option of adding a custom UI template (replaces the buttons) via the customWhiteboardUi input
Features:
- Premade Shapes
- The ability to create custom premade shapes
- Supports touch.
- Supports UNDO/REDO.
- Implements a color picker for stroke and fill colors.
- Sends outputs on every action.
- Contains inputs for multiple modifications.
- Save drawn images
- Custom UI template
- Eraser(experimental)
-
Install npm module:
npm install @drizm/ng-whiteboard --save
-
If you are using system.js you may want to add this into
map
andpackage
config:{ "map": { "@drizm/ng-whiteboard": "node_modules/@drizm/ng-whiteboard" }, "packages": { "@drizm/ng-whiteboard": { "main": "index.js", "defaultExtension": "js" } } }
Add the module to your project
@NgModule({
imports: [
CanvasWhiteboardModule
]
...
)}
In your component, you should add the CanvasWhiteboardComponent as a view provider
@Component({
selector: '...',
viewProviders: [CanvasWhiteboardComponent],
templateUrl: '...'
})
In the html file, you can insert the Canvas Whiteboard
<drizm-whiteboard #canvasWhiteboard
[customWhiteboardUi]="customWhiteboardUiT"
[drawButtonClass]="'drawButtonClass'"
[drawButtonText]="'Draw'"
[clearButtonClass]="'clearButtonClass'"
[clearButtonText]="'Clear'"
[undoButtonText]="'Undo'"
[undoButtonEnabled]="true"
[redoButtonText]="'Redo'"
[redoButtonEnabled]="true"
[colorPickerEnabled]="true"
[fillColorPickerText]="'Fill'"
[strokeColorPickerText]="'Stroke'"
[saveDataButtonEnabled]="true"
[saveDataButtonText]="'Save'"
[lineWidth]="5"
[strokeColor]="'rgb(0,0,0)'"
[shouldDownloadDrawing]="true"
(batchUpdate)="sendBatchUpdate($event)"
(clear)="onCanvasClear()"
(undo)="onCanvasUndo($event)"
(redo)="onCanvasRedo($event)">
</drizm-whiteboard>
<ng-template #customWhiteboardUiT></ng-template>
If there is too much overhead with inputs, you can just specify the [options] input, and specify the options from the typescript code
Example:
<drizm-whiteboard #canvasWhiteboard
[options]="canvasOptions"
(batchUpdate)="onCanvasDraw($event)"
(clear)="onCanvasClear()"
(undo)="onCanvasUndo($event)"
(redo)="onCanvasRedo($event)">
</drizm-whiteboard>
Code:
canvasOptions: CanvasWhiteboardOptions = {
customWhiteboardUi: this.customWhiteboardUiT,
drawButtonEnabled: true,
drawButtonClass: "drawButtonClass",
drawButtonText: "Draw",
clearButtonEnabled: true,
clearButtonClass: "clearButtonClass",
clearButtonText: "Clear",
undoButtonText: "Undo",
undoButtonEnabled: true,
redoButtonText: "Redo",
redoButtonEnabled: true,
colorPickerEnabled: true,
fillColorPickerText: "Fill",
strokeColorPickerText: "Stroke",
saveDataButtonEnabled: true,
saveDataButtonText: "Save",
lineWidth: 5,
strokeColor: "rgb(0,0,0)",
shouldDownloadDrawing: true,
eraserLineWidth: "10",
eraseButtonEnabled: true,
eraseButtonClass: "eraseButtonClass",
eraseButtonText: "Erase"
};
The canvas drawing is triggered when the user touches the canvas, draws (moves the mouse or finger) and then stops drawing. When the drawing is started, after 100 ms all the signals in between are added to a list and are sent as a batch signal which is emitted by the onBatchUpdate emitter. If received, the user can then manipulate with the sent signals.
The time in milliseconds that a batch update should be sent after drawing.
The path to the image. If not specified, the drawings will be placed on the background color of the canvas. This path can either be a base64 string or an actual path to a resource
If specified, the canvas will be resized according to this ratio
If specified, replaces whiteboard buttons with your custom template. To add undo/redo etc. triggers you can get CanvaswhiteboardComponent like this:
@ViewChild('canvasWhiteboard') canvasWhiteboard: CanvasWhiteboardComponent;
and use its public redoLocal and undoLocal methods, along with others.
drawButtonClass: string
clearButtonClass: string
undoButtonClass: string
redoButtonClass: string
saveDataButtonClass: string
eraseButtonClass: string
The classes of the draw, clear, undo and redo buttons. These classes are used in "<i>" tags.
Example:
[drawButtonClass]="'fa fa-pencil fa-2x'"
[clearButtonClass]="'fa fa-eraser fa-2x canvas_whiteboard_button-clear'"
drawButtonEnabled: boolean
(default: true)
clearButtonEnabled: boolean
(default: true)
eraseButtonEnabled: boolean
(default: true)
undoButtonEnabled: boolean
(default: false)
redoButtonEnabled: boolean
(default: false)
saveDataButtonEnabled: boolean
(default: false)
Specifies whether or not the button for drawing or clearing the canvas should be shown.
drawButtonText, clearButtonText, undoButtonText, redoButtonText, saveDataButtonText, eraseButtonText
Specify the text to add to the buttons, default is no text
[drawButtonText]="'Draw'"
[clearButtonText]="'Clear'"
##Use the options: CanvasWhiteboardOptions to send the inputs Changes to this object will be detected by the canvas in the OnChange listener and will be changed accordingly
//Component
canvasOptions: CanvasWhiteboardOptions = {
drawButtonEnabled: true,
drawButtonClass: 'drawButtonClass',
drawButtonText: 'Draw',
clearButtonEnabled: true,
clearButtonClass: 'clearButtonClass',
clearButtonText: 'Clear',
undoButtonText: 'Undo',
undoButtonEnabled: true,
redoButtonText: 'Redo',
redoButtonEnabled: true,
colorPickerEnabled: true,
saveDataButtonEnabled: true,
saveDataButtonText: 'Save',
lineWidth: 4,
scaleFactor: 1
};
//View
<drizm-whiteboard #canvasWhiteboard
[options]="canvasOptions"
(onBatchUpdate)="onCanvasDraw($event)"
(onClear)="onCanvasClear()"
(onUndo)="onCanvasUndo($event)"
(onRedo)="onCanvasRedo($event)"
(onSave)="onCanvasSave($event)">
</drizm-whiteboard>
NOTE: In order for the changeDetection to pick up the options changes, you must change the options reference whenever you want to change a value. Example:
public changeOptions(): void {
this.canvasOptions = {
...this.canvasOptions,
fillColorPickerEnabled: true,
colorPickerEnabled: false
};
}
Each button has its on class (example: Draw button -> .canvas_whiteboard_button-draw)
This button can be customized by overriding its css
.canvas_whiteboard_button-draw:before {
content: "Draw";
}
will add the "Draw" text to the button.
If using component-only styles, for this to work the viewEncapsulation must be set to None.
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
encapsulation: ViewEncapsulation.None
})
You can also use the ::ng-deep
selector if you do not want to change the ViewEncapsulation property on the component.
This shows/hides the fill color picker. Note: if this field has been to false
, but the colorPickerEnabled
field has been to true
, the color picker will be shown, as per reverse-compat needs.
Specify the text to add to the fill color picker button. Default is 'Fill' for reverse-compat needs.
This shows/hides the stroke color picker. Note: if this field has been to false
, but the colorPickerEnabled
field has been set to true
, the color picker will be shown, as per reverse-compat needs.
Specify the text to add to the stroke color picker button. Default is 'Stroke' for reverse-compat needs.
This input controls the drawing pencil size
This input control the color of the brush
This input control the background color of the shapes
This input control if the image created when clicking the save button should be downloaded right away.
This input control is used to fill the canvas with the specified color at initialization and on resize events.
This input controls the generation of the X and Y coordinates with a given scaleOffset. If not provided, the current with and height of the bounding rect and the canvas object will be used so that it works when transforming the canvas with css.
This input controls if the drawing should be enabled from the start, instead of waiting for the user to click draw
This input controls if the CanvasWhiteboardColorPickerComponent for the strokeColor
should be shown programmatically
This input controls if the CanvasWhiteboardColorPickerComponent for the fillColor
should be shown programmatically
This input controls the name of the file that will be downloaded when an image is saved.
If the downloadCanvasImage
method is called with a fileName
as a third parameter, then it will have priority over everything
If the fileName
is not provided, then this Input will have priority. If this input is not provided as well,
the image will be saved as canvas_drawing_" + new Date().valueOf()
;
At the end the file extension will be added so that it can be opened by a particular app.
The lineJoin property sets or returns the type of corner created, when two lines meet.
The lineCap property sets or returns the style of the end caps for a line.
This input controls if the CanvasWhiteboardShapeSelectorComponent will be enabled so that the user can pick other shapes via the View
This input controls if the CanvasWhiteboardShapeSelectorComponent should be shown programmatically
@Output() onClear = new EventEmitter<any>();
@Output() onBatchUpdate = new EventEmitter<CanvasWhiteboardUpdate[]>();
@Output() onImageLoaded = new EventEmitter<any>();
@Output() onUndo = new EventEmitter<any>();
@Output() onRedo = new EventEmitter<any>();
@Output() onSave = new EventEmitter<string | Blob>();
onClear
is emitted when the canvas has been cleared.
onImageLoaded
is emitted if the user specified an image and it has successfully been drawn on the canvas.
onUndo
is emitted when the canvas has done an UNDO function, emits an UUID (string) for the continuous last drawn shape undone.
onClear
is emitted when the canvas has done a REDO function, emits an UUID (string) for the continuous shape redrawn.
onSave
is emitted when the canvas has done a SAVE function, emits a Data URL or a Blob (IE).
Every shape in the application extends the abstract class CanvasWhiteboardShape
. This class adds predefined methods so that
the creator of the shape can follow them and decide how his shape should be drawn.
Each shape is made of a starting position point of type CanvasWhiteboardPoint
, and an options object
which may be different for each shape, and it's of type CanvasWhiteboardShapeOptions
.
Each predefined shape must know how to:
- Return the name of the shape (should be the same as the name of the class)
- Draw itself given a canvas context
- Draw it's preview given a canvas context
- Update itself given a
CanvasWhiteboardUpdate
All of the predefined shapes are registered and available in the CanvasWhiteboardShapeService which the user can have to register/unregister additional shapes.
To create a new shape, you must create a class which extends the abstract class CanvasWhiteboardShape
.
From there you need to implement the required methods.
After all of this is complete, you need to register this shape in the canvas whiteboard shape service (for the sake of convention).
class AppComponent {
constructor(private _canvasWhiteboardService: CanvasWhiteboardService, private _canvasWhiteboardShapeService: CanvasWhiteboardShapeService) {
_canvasWhiteboardShapeService.registerShape(RandomShape);
}
}
export class RandomShape extends CanvasWhiteboardShape {
linePositions: Array<number>;
constructor(positionPoint?: CanvasWhiteboardPoint, options?: CanvasWhiteboardShapeOptions) {
// Optional constructor if you need some additional setup
super(positionPoint, options);
this.linePositions = [];
}
getShapeName(): string {
// Abstract method which should return a string with the shape name
// Should be the same as the class name
return 'RandomShape';
}
draw(context: CanvasRenderingContext2D): any {
// Tell the canvas how to draw your shape here
// Use the selected options from the canvas whiteboard
// Object.assign(context, this.options);
// Start drawing
// context.save();
// context.beginPath();
// context.stroke();
// context.fill();
// context.closePath();
// context.restore();
}
drawPreview(context: CanvasRenderingContext2D): any {
// Provide info or update this object when it's needed for preview drawing.
// Example: The CIRCLE selects the center point and updates the radius.
// Example: The RECT selects 0,0 and updates width and height to 100%.
// Then call the draw method with the updated object if you want your shape
// to have a proper preview.
// this.draw(context);
}
onUpdateReceived(update: CanvasWhiteboardUpdate): any {
// Choose what your shape does when an update is registered for it
// For example the CircleShape updates it's radius
}
onStopReceived(update: CanvasWhiteboardUpdate): void {
// This method is optional but CAN be overriden
}
}
The default shapes can also be unregistered. Example:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private canvasWhiteboardShapeService: CanvasWhiteboardShapeService) {
this.canvasWhiteboardShapeService.unregisterShapes([CircleShape, SmileyShape, StarShape]);
}
}
NOTE: There must be at least one shape registered for the canvas to work, but for the sake of convenience, all of the default shapes have been exported (maybe someone would want to unregister all of them and register his own shapes), but it is recommended not to unregister the FreeHandShape.
The CanvasWhiteboardComponent
is now equipped with a shape selector (since the free hand drawing is now a shape because of consistency),
The shape selector can be managed or hidden with inputs, and it basically calls the CanvasWhiteboardShapeService
and draws all the
registered shapes so that they can be selected. They are drawn with the selected fill/stroke color for preview.
The CanvasWhiteboardService
will be used by the canvas to listen to outside events.
The event emitters and ViewChild functionality will remain the same but with this service
we can notify the canvas when it should invoke a specific action
Example:
export class AppComponent {
constructor(private _canvasWhiteboardService: CanvasWhiteboardService) {}
public receiveNewMessage(newMessage: any): void {
switch (newMessage.type) {
case VCDataMessageType.canvas_draw:
let updates = newMessage.data.map(updateJSON => CanvasWhiteboardUpdate.deserializeJson(JSON.parse(updateJSON)));
this._canvasWhiteboardService.drawCanvas(updates);
break;
case VCDataMessageType.canvas_clear:
this._canvasWhiteboardService.clearCanvas();
break;
case VCDataMessageType.canvas_undo:
this._canvasWhiteboardService.undoCanvas(newMessage.UUID);
break;
case VCDataMessageType.canvas_redo:
this._canvasWhiteboardService.redoCanvas(newMessage.UUID);
break;
}
}
}
Can be called via the method getDrawingHistory(): CanvasWhiteboardUpdate[]
. The items will be deep cloned for consistency using lodash.
In order to save drawn images you can either click the Save button in the canvas, use the short Ctrl/Command + s key or get a reference of the canvas and save programmatically.
Example, save an image whenever an undo action was made:
HTML: Create a canvas view reference with some name (ex: #canvasWhiteboard)
<drizm-whiteboard #canvasWhiteboard>
</drizm-whiteboard>
import {CanvasWhiteboardComponent} from '@drizm/ng-whiteboardd';
export class AppComponent {
@ViewChild('canvasWhiteboard') canvasWhiteboard: CanvasWhiteboardComponent;
onCanvasUndo(updateUUID: string) {
console.log(`UNDO with uuid: ${updateUUID}`);
//Returns base64 string representation of the canvas
let generatedString = this.canvasWhiteboard.generateCanvasDataUrl("image/jpeg", 0.3);
//Generates a IE canvas blob using a callbak method
this.canvasWhiteboard.generateCanvasBlob((blob: any) => {
console.log(blob);
}, "image/png");
//This method uses both of the above method and returns either string or blob
//using a callback method
this.canvasWhiteboard.generateCanvasData((generatedData: string | Blob) => {
console.log(generatedData);
}, "image/png", 1);
//This method downloads the image using either existing data if it exists
//or creates it locally
this.canvasWhiteboard.downloadCanvasImage("image/png", existingData?, "customFileName");
//If you need the context of the canvas
let context = this.canvasWhiteboard.context;
}
}
A canvas component that is used to identify and emit selected colors.
@Input() selectedColor: string (default: "rgb(0,0,0)");
@Output() onColorSelected = new EventEmitter<string>();
An example of a drawn image and shape on the canvas with additional css for the buttons and a date:
- If there are problems with the sizing of the parent container, the canvas size will not be the wanted size. It may sometimes be width: 0, height: 0. If this is the case you may want to call a resize event for the window for the size to be recalculated.
if (this.isCanvasOpened) {
setTimeout(() => {
window.dispatchEvent(new Event('resize'));
}, 1);
}