LOADING...

Preview

Pen ID
Unlock Campus Themeforest adv

 

Code


CSS
.head-tracker {  
  position: relative;
  display: inline-block;
}
  
  .head-tracker video {
    display: none;
  }
  
  .head-tracker canvas {
    position: relative;
  }
  
  .head-tracker canvas:nth-child(2) {
      position: absolute;
      top: 0;
    }
  
  .head-tracker .debug-point {
    position: absolute;
    top: 0;
    left: 0;
    width: 10px;
    height: 10px;
    margin-top: -5px;
    margin-left: -5px;
    background: red;
  }
  
  .head-tracker .debug-output {
    position: absolute;
    top: 0;
    left: 0;
    color: white;
    font-size: 3em;
  }

JS
import Vector from 'https://cdn.rawgit.com/sbrl/69a8fa588865cacef9c0/raw/94ac455bbc72cd05e56021f42aacd438599d627e/Vector.js';
import Buffer from 'https://codepen.io/StephanGerbeth/pen/PReMXb.js';

const nodes = new Map();
let matrix = new WebKitCSSMatrix();
//const minX = 0.28;
//const maxX = 0.5;
//const minY = 0.3;
//const maxY = 0.5;
const camBounds = {
  min: { x: 0.223, y: 0.34 }, 
  max: { x: 0.56, y: 0.475 }
};

export let buffer = new Buffer(5, adjustToCamBounds(new Vector(0.5, 0.5), camBounds));

class HeadTracker {
  
  constructor() {
    this.video = getElement('.head-tracker > video');
    this.video.addEventListener("playing", updateSize);
  } 
  
  enable() {        
    var htracker = new headtrackr.Tracker({
      calcAngles : false, 
      ui : false, 
      headPosition : true, 
      debug: getElement('.head-tracker > .debug')
    });
    
    htracker.init(getElement('.head-tracker > video'), getElement('.head-tracker > .compare'));
    htracker.start();
    
    document.addEventListener("facetrackingEvent", ( e ) => trackFace.bind(this)(e), false);
  }
}

function getElement(selector) {
  if(!nodes.has(selector)) {
    let el = document.body.querySelector(selector);
    nodes.set(selector, el);
  }
  return nodes.get(selector);
}

function updateSize(e) {  
  nodes.forEach((item) => {    
    item.setAttribute('width', e.target.videoWidth);
    item.setAttribute('height', e.target.videoHeight);
  });
}

function trackFace(e) {
  let video = getElement('.head-tracker > video'); 
  let v = new Vector(e.x, e.y);
  v.divide(video.videoWidth, video.videoHeight);
  v = adjustToCamBounds(v, camBounds);
  buffer.add(v);
  
  let point = buffer.average();
  document.body.querySelector('.debug-output').innerHTML = point.x.toFixed(3) + ' : ' + point.y.toFixed(3);
  
  document.body.querySelector('.head-tracker > .debug-point').style.transform = matrix.translate(e.x, e.y, 0);
  
}

function adjustToCamBounds(vector, bounds) {
  vector.x = (vector.x - bounds.min.x) / (bounds.max.x - bounds.min.x);
  vector.y = (vector.y - bounds.min.y) / (bounds.max.y - bounds.min.y);
  return vector;
}

let headTracker = new HeadTracker();
headTracker.enable();
Term
Sat, 04/14/2018 - 20:47

Related Codes

Pen ID
Pen ID
Pen ID
Square Adv