JSFiddle - React, Tailwind, and code Playground
by morphcast
HTML
<script src="https://ai-sdk.morphcast.com/dev/ai-sdk.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.2.0/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<body>
<div class="container-fluid">
<div class="row">
<canvas id="canvas" class="col-md-8"></canvas>
<br />
<div class="col-md-4">
<strong>MorphCast JS SDK - Frame crop capture and download (dev environment)</strong>
</div>
</div>
<div>
<button id="start" onclick="onStart()" disabled>Start</button>
<button id="stop" onclick="onStop()">Stop</button>
<p>
<strong>Instructions</strong>
Press the start button to start the detector.
<br/> Press the stop button to end the detector.
</p>
<div>
<strong>LOG:</strong>
</div>
<div id="logs"></div>
</div>
</div>
</body>
JavaScript
const MAX_FRAMES = 100;
function log(msg) {
var element = document.getElementById("logs");
element.innerHTML += "<span>" + msg + "</span><br />";
}
function print(node, msg) {
document.getElementById(node).innerHTML = msg;
}
//function executes when Start button is pushed.
function onStart() {
if (detector && !detector.isRunning) {
detector.isRunning = true;
detector.start();
}
log("Start acquiring " + MAX_FRAMES + " frames.");
frame_array = [];
downloaded = false;
}
//function executes when the Stop button is pushed.
function onStop() {
log("Stopped");
if (detector && detector.isRunning) {
detector.stop();
detector.isRunning = false;
}
}
const ctx = document.getElementById('canvas').getContext('2d');
let dimLogged = false;
/*window.addEventListener(CY.modules().CAMERA.eventName, (evt) => {
const imageData = evt.detail;
if (!dimLogged) {
log(`Camera dimensions: w: ${imageData.width}, h: ${imageData.height}`);
dimLogged = true;
}
ctx.canvas.width = imageData.width;
ctx.canvas.height = imageData.height;
ctx.putImageData(imageData, 0, 0);
});*/
let frame_array = [];
let downloaded = false;
window.addEventListener(CY.modules().FACE_DETECTOR.eventName, (evt) => {
const imageData = evt.detail.faces[0];
if(imageData) {
if (!dimLogged) {
log(`Camera dimensions: w: ${imageData.width}, h: ${imageData.height}`);
dimLogged = true;
}
ctx.canvas.width = imageData.width;
ctx.canvas.height = imageData.height;
ctx.putImageData(imageData, 0, 0);
if (frame_array.length < MAX_FRAMES) {
frame_array.push(ctx.canvas.toDataURL("image/png"));
}
if (frame_array.length === MAX_FRAMES && !downloaded) {
downloadAll(frame_array);
downloaded = true;
onStop();
log("Downloading frames.");
}
}
});
var detector = {};
detector.isRunning = false;
function FormatNumberLength(num, length) {
var r = "" + num;
while (r.length < length) {
...