Building a Canvas component with Free Hand drawing using RxJS and Angular

Tarik A
2 min readApr 1, 2017

--

The output of the component

Edit: Updated for Angular 12! (2021–06–03)

You probably already know the Canvas elements can be used to draw graphics. I’m going to demonstrate how we can use RxJS to draw free hand and turn it into an Angular component without using any external libraries.

If you want to head straight into the code, here is the plunkr example (see canvas.component.ts): https://stackblitz.com/edit/angular-rxjs-canvas-v12?file=src%2Fapp%2Fcanvas.component.ts

I’ll try not to focus too much into styling and the noise around the main functionality, I’ll leave that up to you. All we’ll concentrate on is actually capturing the right events, and using the Canvas Context to draw the points between those mouse events. The scope of this article will only cover mouse events and not touch events.

Creating the Component

First let’s create our component with our canvas element:

Capturing the Events

Now we’ll need to listen to the events we require from the mouse to know when the user is actually drawing.

The three events we need to capture are:

  • Mouse down — when the user has first click down the mouse
  • Mouse move — the user’s mouse movement
  • Mouse up — when the user has released the mouse click
  • Mouse leave — when the mouse has left the canvas

Our event stream will basically be, we listen for `mousedown`, once we’ve captured that then we’ll start listening for `mousemove`, and take events until `mouseup` or `mouseleave`.

Ensure you import the RxJS operators required:

import { fromEvent } from 'rxjs';import { switchMap, takeUntil, pairwise } from 'rxjs/operators'

From this we get our current position and previous position, we’ll need to use those positions to draw a line that connects the two points. As a stream of data comes in, you can see that we’re just connecting the dots between the positions to actually generate the drawing.

Drawing on the Canvas

Here is how to draw using the canvas context:

Drawing is straight forward, we are really mapping two points with a path, and stroking the path with the styles we’ve set.

And that’s it!

Final Words

Its important to note that we don’t really use any Angular specific features, the same example can be replicated with pure JS and RxJS. These are the raw HTML Canvas API’s we’re using to actually draw and we are using RxJS to capture standard events coming from an HTML elements.

See the example in all its glory in here: https://stackblitz.com/edit/angular-rxjs-canvas-v12?file=src%2Fapp%2Fcanvas.component.ts

Let me know if you have any questions!

Need more help? You can reach me at alani.co.nz.

--

--