Initializing the Display Components

Before we can build more shape drawers, we first need a way to display the existing drawers in a "toolbar" so the user can select which one they want. We need a lot of pieces to make this work, so let's get started building them.

The first thing we need is a class that represents each displayed option. We are calling these classes "display components" and we need a base one from which all specific components can inherit. This class will need some properties that allow us to set up things like the CSS classes and icon displayed, as well as set the Drawing Mode.

Here's the annotated code for this base class, called DisplayComponent:

This class implements an SVG definition for the component's icon, and saves the alt text, before using super() to call the parent class DisplayComponent's constructor.

Showing the Display Components

We're halfway to being able to, ahem, display the display components. Now we need to make some changes to the main DrawingEditor class.

We want our DrawingEditor (which, as a reminder, represents the drawing area as a whole, including our display components) to be able to initialize components at creation time. To do this, we're going to create two methods:

The method componentSelected() needs to be implemented on DrawingEditor. We do that like this:

class DrawingEditor {
//...Properties and Methods
componentSelected(componentName: string) {
//Deselect any objects on the canvas that are selected
this.canvas.discardActiveObject();
//FOREACH component in the drawing editor...
for (var key in this.components) {
// IF this component has a property with the passed-in name
// THEN do nothing
if (!this.components.hasOwnProperty(key)) continue;
//OTHERWISE...
const obj = this.components[key];
//IF the component with the passed-in name
//IS the component we expect
if (obj[0].target === componentName) {
//SET the drawing mode to the drawing mode
//needed by the component
this.drawingMode = obj[0].drawingMode;
}
//IF the method selectedChanged is defined on the component,
//THEN call that method
if (obj[0].selectedChanged !== undefined) {
obj[0].selectedChanged(componentName);
}
}
}
}

HTML and Script

We have one last piece we need to do to set up our first display component: we need to insert some HTML and some JavaScript on our Razor Page where we want to make a drawing.

Next up in this series, we'll make a new component that will allow us to delete objects from the canvas, and implement hotkey functionality for the same. Check out Part 3 of Drawing with FabricJS and TypeScript!