JSFiddle - React, Tailwind, and code Playground

by uedatakuya

HTML

<script src="https://dl.dropboxusercontent.com/u/2219262/facedetection/aruco.js"></script>
<script src="https://dl.dropboxusercontent.com/u/2219262/facedetection/ccv.js"></script>
<script src="https://dl.dropboxusercontent.com/u/2219262/facedetection/face.js"></script>
<script src="https://dl.dropboxusercontent.com/u/2219262/facedetection/gopher_head.js"></script>
<!-- ko if: isStarted -->
<div class="btn" data-bind="click: stop">Stop</div>
<!-- /ko -->
<!-- ko ifnot: isStarted -->
<div class="btn" data-bind="click: start">Start</div>
<!-- /ko -->

<video id="video-src" autoplay=""></video>
<canvas id="video-dest"></canvas>

CSS

#video-src {
    display: none;
}

.btn {
    width: 100px;
    height: 50px;
    background-color: rgb(80,80,80);
    color:white;
    text-align: center;
    font-size:32px;
}

JavaScript

var FaceDetection = (function () {

    var image = new Image();
   image.src = gopher_head;

    function FaceDetection(callback) {
        this.intervalObj = null;
        this.video = {
            src: document.getElementById("video-src"),
            dest: document.getElementById("video-dest")
        };
        
        this.isStarted = ko.observable(false);

        this.callback = callback || function () {};
    }

    function onGotStream(stream) {
        var url = webkitURL.createObjectURL(stream);
        this.video.src.src = url;
        this.intervalObj = window.setInterval(detection.bind(this), 500);
    };

    function onFailedStream(error) {
        alert("onFailedStream");
    };

    function detection() {

        var width = this.video.src.videoWidth;
        var height = this.video.src.videoHeight;

        this.video.dest.width = width;
        this.video.dest.height = height;

        var context = this.video.dest.getContext('2d');
        context.drawImage(this.video.src, 0, 0, width, height);

        var comp = ccv.detect_objects({
            "canvas": this.video.dest,
                "cascade": cascade,
                "interval": 5,
                "min_neighbors": 1
        });

        if (comp.length > 0) {
            context.drawImage(image, comp[0].x - 30, comp[0].y - 30, comp[0].width + 60, comp[0].height + 60);
            this.callback(comp[0]);
        }

    };

    FaceDetection.prototype.start = function () {
        this.isStarted(true);
        window.navigator.webkitGetUserMedia({
            audio: true,
            video: true
        },
        onGotStream.bind(this),
        onFailedStream.bind(this));
    };

    FaceDetection.prototype.stop = function () {
        this.isStarted(false);
        this.intervalObj && window.clearInterval(this.intervalObj);
        this.intervalObj = null;
    };

    return FaceDetection;
})();

var fd = new FaceDetection(function () {  
    //this.stop();
});

ko.applyBindings(fd);