eduardolundgren/tracking.js

Angular Example

luiza-avelino opened this issue · 0 comments

For anyone who needs, I have a angular code that works with tracking js:

HTML:
`


<video
#video
id="video"
width="400"
height="400"
preload
autoplay
loop
muted

<canvas #canvas id="canvas" width="400" height="400">

`

TypeScript:

`import {
Component,
AfterViewInit,
OnDestroy,
ViewChild,
ElementRef
} from "@angular/core";

import "tracking";
import "tracking/build/data/face";

declare var window: any;
declare var tracking: any;

@component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterViewInit, OnDestroy {
@ViewChild("video") webcam: ElementRef;
@ViewChild("canvas") canvas: ElementRef;
@ViewChild("canvasContext") canvasContext: ElementRef;

title = "app";
private mediaStream: Promise;

constructor() {
this.mediaStream = navigator.mediaDevices.getUserMedia({ video: true });
}
async ngAfterViewInit() {
this.track();
}

async track() {
this.webcam.nativeElement.srcObject = await this.mediaStream;
const video = this.webcam.nativeElement;
const canvas = this.canvas.nativeElement;
const context = canvas.getContext("2d");
const tracker = new tracking.ObjectTracker("face");

tracker.setInitialScale(1);
tracker.setStepSize(1);
tracker.setEdgesDensity(0.1);

let trackingTask = tracking.track("#video", tracker, { camera: true });
tracker.on("track", event => {
  context.clearRect(0, 0, canvas.width, canvas.height);
  if (event.data.length != 0) {
    let target = event.data[0];
    context.strokeStyle = "#ff0000";
    context.lineWidth = 2;
    context.strokeRect(target.x, target.y, target.width, target.height);
    let canvasScreen = document.createElement("canvas");
    canvasScreen.width = 400;
    canvasScreen.height = 400;
    var ctx = canvasScreen.getContext("2d");
    ctx.drawImage(video, 0, 0, canvasScreen.width, canvasScreen.height);
  }
});

}

async ngOnDestroy() {}
}
`

Angular Version: 5.2