JSFiddle - React, Tailwind, and code Playground
by morphcast
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/smoothie/1.34.0/smoothie.min.js"></script>
<script src="https://ai-sdk.morphcast.com/v1.8.3/ai-sdk.js"></script>
<body>
<div class="container-fluid">
<div class="row">
<canvas id="canvas" class="col-md-8"></canvas>
<br />
<canvas id="chart_age" width="400" height="250"></canvas>
<div class="col-md-4">
<strong>MorphCast JS SDK - Age module (v1.8.3 environment) - Proof-of-concept for Vodafone use case</strong>
<div id="age_results" style="word-wrap:break-word;font-size:40px"></div>
<div id="gender_results" style="word-wrap:break-word;font-size:40px"></div>
</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
function log(msg) {
var element = document.getElementById("logs");
element.innerHTML += "<span>" + msg + "</span><br />";
}
let timeout;
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("Clicked the start button");
print("age_results", "Age: --");
print("gender_results", "Gender: --");
}
//function executes when the Stop button is pushed.
function onStop() {
log("Clicked the stop button");
if (detector && detector.isRunning) {
detector.stop();
detector.isRunning = false;
}
}
window.addEventListener(CY.modules().FACE_AGE.eventName, (evt) => {
const numericAge = evt.detail.output.numericAge;
const age = numericAge || '--';
print("age_results", "Age: " + age);
if(numericAge) {
log('Event [AGE] sent to App: ' + numericAge );
}
ts_age.append(new Date().getTime(), numericAge);
ts_rawAge.append(new Date().getTime(), evt.detail.output.rawAge);
});
let gender_results = 0;
window.addEventListener(CY.modules().FACE_GENDER.eventName, (evt) => {
const MIN_GENDER_RESULTS = 20;
gender_results += 1;
if (gender_results >= MIN_GENDER_RESULTS) {
const gender = evt.detail.output.gender || '--';
const string_gender = JSON.stringify(gender, function(key, val) {
return val.toFixed ? Number(val.toFixed(2)) : val;
});
print("gender_results", "Gender: " + string_gender);
log('Event [GENDER] sent to App: ' + string_gender);
}
});
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;
...