Drawing the key points on the canvas

Whenever we detect a pose, we receive a number of key points back with it. Each key point is made up of a position (the x and y coordinates), the score (or confidence), and the actual part that the key point represents. We want to loop over the points and draw them on the canvas.

As always, let's start off with our class definition:

export class DrawPose {
}

We only need to get the canvas element once as it's not going to change. This indicates that we could pass this as our canvas and, because we are interested in the two-dimensional element of the canvas, we can extract the drawing context directly from the canvas. With this context, we clear off any previously drawn elements on the canvas and set a fillStyle color to #ff0300, which we will use to color in our pose points:

constructor(private canvas: HTMLCanvasElement, private context = canvas.getContext('2d')) {
this.context!.clearRect(0, 0, this.canvas.offsetWidth, this.canvas.offsetHeight);
this.context!.fillStyle = '#ff0300';
}

In order to draw our key points, we write a method that loops over each Keypoint instance and calls fillRect to draw the point. The rectangle is offset from the x and y coordinates by 2.5 pixels so that drawing a 5-pixel rectangle actually draws a rectangle that is roughly centered on the point:

public Draw(keys: Keypoint[]): void {
keys.forEach((kp: Keypoint) => {
this.context!.fillRect(kp.position.x - 2.5,
kp.position.y - 2.5, 5, 5);
});
}

Once finished, our DrawPose class looks like this:

export class DrawPose {
constructor(private canvas: HTMLCanvasElement, private context =
canvas.getContext('2d')) {
this.context!.clearRect(0, 0, this.canvas.offsetWidth,
this.canvas.offsetHeight);
this.context!.fillStyle = '#ff0300';
}

public Draw(keys: Keypoint[]): void {
keys.forEach((kp: Keypoint) => {
this.context!.fillRect(kp.position.x - 2.5,
kp.position.y - 2.5, 5, 5);
});
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.98.71