Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="loadOverlay">
    <div class="container">
      <div class="loaderBox">
        <div id="shell1"></div>
        <div id="shell2"></div>
        <div id="shell3"></div>
        <div id="shell4"></div>
        <div id="shell5"></div>
        <div id="shell6"></div>
        <div id="shell7"></div>
        <div id="shell8"></div>
        <div id="shell9"></div>
        <div id="shell10"></div>
        <p class="greenText">loading...</p>
      </div>
    </div>
  </div> 

<div class="selectionWrapper">
    <div class="select">
    <label for="videoSource">📷: </label>
    <select id="videoSource"></select>
  </div>
</div>
  <p class="hidden">
    The MobileNet model labeled this as <span id="result">...</span>
    <br />with a confidence of <span id="probability">...</span>.
  </p>
  <video id="video" height="100%" width="100%" autoplay></video>
  <div id="results"></div>
  <div id="chartContainer">
    <canvas id="canvas1"></canvas>
  </div>
              
            
!

CSS

              
                html, body {
  margin: 0;
  padding: 0;
  /*background-color:rgb(20,20,20);*/
}
body{
  overflow:hidden;
}
.selectionWrapper{
  z-index:100;
  position:absolute;
  top:0%;
  left:0%;
  margin-top:10px;
}
#results{
  position:absolute;
  top:0%;
  right:0%;
  margin-top:10px;
  margin-right:10px;
  height:10px;
  width:10px;
  background-color:red;
  border-radius:100vw;
  z-index:100;
}
.wikiLink{
  height:30px;
}
.wikiLink:hover{
  opacity:0.6;
}
video{
  position:absolute;
  left:0%;
  top:0%;
  width:100%;
  transform-origin: top left;
  z-index:1;
}
#canvas1{
  margin-bottom:20px;
}
#chartContainer{
  position:absolute;
  bottom:0%;
  left:50%;
  transform:translate(-50%,0%);
  height:30vh;
  display:block;
  width:100%;
  padding:10px;
  z-index:200;
  background-color:rgba(0,0,0,0.6);
}
.hidden{
  display:none;
}

.swal-overlay {
  background-color: rgba(43, 165, 137, 0.45);
}

#loadOverlay{
  height:100%;
  width:100%;
  position:absolute;
  z-index:1000;
  background-color:BLACK;
}



/*Camera CSS*/
div.select {
  margin: 0 0 1em 0;
}
#container{
  background-color:rgb(200,200,200);
  text-align:center;
}
.select{
  text-align:left;
  padding-left:10px;
  z-index:100;
}
#videoSource #result{
  z-index:100;
}



/*Loader CSS*/
.greenText{
  color:rgba(0,255,0,1);
  text-align:center;
  position:absolute;
  top:120%;
  left:50%;
  transform:translate(-50%,-50%);
}

.loaderBox{
  transform:translate(-50%,-50%);
  margin:10px;
  position:absolute;
  top:50%;
  left:50%;
  /*the shapes are all percentages of this height/width box. Increase/decrease these dimensions as needed*/
  height:20vh;
  width:20vh;
}

/*Shell*/
#shell1{
  position:absolute;
  height:100%;
  width:100%;
  top:50%;
  left:50%;
  transform:translate(-50%, -50%);
  border-radius:100%;
  background:linear-gradient(rgba(0,0,0,0) 50%, rgba(0,255,0,1) 50%);
  animation: shell1a 10s linear infinite;
}
#shell2{
  position:absolute;
  height:90%;
  width:90%;
  top:50%;
  left:50%;
  transform:translate(-50%, -50%);
  border-radius:100%;
  background:linear-gradient(rgba(0,0,0,0) 50%, rgba(0,229.5,0,1) 50%);
  animation: shell2a 10s linear infinite;
}
#shell3{
  position:absolute;
  height:80%;
  width:80%;
  top:50%;
  left:50%;
  transform:translate(-50%, -50%);
  border-radius:100%;
  background:linear-gradient(rgba(0,0,0,0) 50%, rgba(0,204,0,1) 50%);
  animation: shell3a 10s linear infinite;
}
#shell4{
  position:absolute;
  height:70%;
  width:70%;
  top:50%;
  left:50%;
  transform:translate(-50%, -50%);
  border-radius:100%;
  background:linear-gradient(rgba(0,0,0,0) 50%, rgba(0,178.5,0,1) 50%);
  animation: shell4a 10s linear infinite;
}
#shell5{
  position:absolute;
  height:60%;
  width:60%;
  top:50%;
  left:50%;
  transform:translate(-50%, -50%);
  border-radius:100%;
  background:linear-gradient(rgba(0,0,0,0) 50%, rgba(0,153,0,1) 50%);
  animation: shell5a 10s linear infinite;
}
#shell6{
  position:absolute;
  height:50%;
  width:50%;
  top:50%;
  left:50%;
  transform:translate(-50%, -50%);
  border-radius:100%;
  background:linear-gradient(rgba(0,0,0,0) 50%, rgba(0,127.5,0,1) 50%);
  animation: shell6a 10s linear infinite;
}
#shell7{
  position:absolute;
  height:40%;
  width:40%;
  top:50%;
  left:50%;
  transform:translate(-50%, -50%);
  border-radius:100%;
  background:linear-gradient(rgba(0,0,0,0) 50%, rgba(0,102,0,1) 50%);
  animation: shell7a 10s linear infinite;
}
#shell8{
  position:absolute;
  height:30%;
  width:30%;
  top:50%;
  left:50%;
  transform:translate(-50%, -50%);
  border-radius:100%;
  background:linear-gradient(rgba(0,0,0,0) 50%, rgba(0,76.5,0,1) 50%);
  animation: shell8a 10s linear infinite;
}
#shell9{
  position:absolute;
  height:20%;
  width:20%;
  top:50%;
  left:50%;
  transform:translate(-50%, -50%);
  border-radius:100%;
  background:linear-gradient(rgba(0,0,0,0) 50%, rgba(0,51,0,1) 50%);
  animation: shell9a 10s linear infinite;
}
#shell10{
  position:absolute;
  height:10%;
  width:10%;
  top:50%;
  left:50%;
  transform:translate(-50%, -50%);
  border-radius:100%;
  background:linear-gradient(rgba(0,0,0,0) 50%, rgba(0,25.5,0,1) 50%);
  animation: shell10a 10s linear infinite;
}
@keyframes shell1a{
  0%{
    transform:translate(-50%, -50%) rotate(0deg);
  }
  100%{
    transform:translate(-50%, -50%) rotate(3600deg);
  }
}
@keyframes shell2a{
  0%{
    transform:translate(-50%, -50%) rotate(0deg);
  }
  100%{
    transform:translate(-50%, -50%) rotate(3240deg);
  }
}
@keyframes shell3a{
  0%{
    transform:translate(-50%, -50%) rotate(0deg);
  }
  100%{
    transform:translate(-50%, -50%) rotate(2880deg);
  }
}
@keyframes shell4a{
  0%{
    transform:translate(-50%, -50%) rotate(0deg);
  }
  100%{
    transform:translate(-50%, -50%) rotate(2520deg);
  }
}
@keyframes shell5a{
  0%{
    transform:translate(-50%, -50%) rotate(0deg);
  }
  100%{
    transform:translate(-50%, -50%) rotate(2160deg);
  }
}
@keyframes shell6a{
  0%{
    transform:translate(-50%, -50%) rotate(0deg);
  }
  100%{
    transform:translate(-50%, -50%) rotate(1800deg);
  }
}
@keyframes shell7a{
  0%{
    transform:translate(-50%, -50%) rotate(0deg);
  }
  100%{
    transform:translate(-50%, -50%) rotate(1440deg);
  }
}
@keyframes shell8a{
  0%{
    transform:translate(-50%, -50%) rotate(0deg);
  }
  100%{
    transform:translate(-50%, -50%) rotate(1080deg);
  }
}
@keyframes shell9a{
  0%{
    transform:translate(-50%, -50%) rotate(0deg);
  }
  100%{
    transform:translate(-50%, -50%) rotate(720deg);
  }
}
@keyframes shell10a{
  0%{
    transform:translate(-50%, -50%) rotate(0deg);
  }
  100%{
    transform:translate(-50%, -50%) rotate(360deg);
  }
}
              
            
!

JS

              
                let con1;
let con2;
let con3;
let res1 = "Top Result";
let res2 = "2nd";
let res3 = "3rd";
let chart;
let num = 0;
let interval = 24;
let freezeIt = false;
let upper90 = false;

var videoSelect = document.querySelector('select#videoSource');

// Grab elements, create settings, etc.
const video = document.getElementById('video');

//only video, no audio
let constraints = {
  video: true
};

// Create a webcam capture
navigator.mediaDevices.enumerateDevices()
  .then(gotDevices).catch(handleError);

//rerun getStream when selection changes
videoSelect.onchange = getStream;

//populate dropdowns with all available devices
function gotDevices(deviceInfos) {
  for (var i = 0; i !== deviceInfos.length; ++i) {
    var deviceInfo = deviceInfos[i];
    
    //create each camera in dropdown
    var option = document.createElement('option');
    //assign id values
    option.value = deviceInfo.deviceId;
    
    //add 'camera '
    if (deviceInfo.kind === 'videoinput') {
      option.text = deviceInfo.label || 'camera ' +
        (videoSelect.length + 1);
      videoSelect.appendChild(option);
    }
  }
}

//start the stream for selection
function getStream() {
  
  if (window.stream) {
    //stop any running streams
    window.stream.getTracks().forEach(function(track) {
      track.stop();
    });
  }
  
  //reset constraints to selected value
  constraints = {
    video: {
      deviceId: {exact: videoSelect.value}
    }
  };
  
  //rerun the video stream with new value
  navigator.mediaDevices.getUserMedia(constraints).
    then(gotStream).catch(handleError);
}

navigator.mediaDevices.getUserMedia(constraints).
    then(gotStream).catch(handleError);


function gotStream(stream) {
  window.stream = stream; // make stream available to console
  video.srcObject = stream;
  video.play();
}

//error handling
function handleError(error) {
  console.log('Error: ', error);
}

// Initialize the Image Classifier method with MobileNet passing the video as the
// second argument and the getClassification function as the third
ml5.imageClassifier('MobileNet', video)
  .then(classifier => loop(classifier))

const loop = (classifier) => {
  classifier.classify()
    .then(results => {
      result.innerText = results[0].label;
      probability.innerText = results[0].confidence.toFixed(4);
      gotResults(results);
      loop(classifier) // Call again to create a loop
    })
}


// When the model is loaded
function modelLoaded() {
  //hide loading screen
  //document.getElementById("loadOverlay").style.display = "none";
  alert("loaded");
}


//chart gradient stuff
var bar_ctx = document.getElementById('canvas1').getContext('2d');
var green_gradient = bar_ctx.createLinearGradient(0, 0, 600, 0);
green_gradient.addColorStop(0, 'rgb(35, 136, 35)');
green_gradient.addColorStop(1, 'rgb(0,255,0)');
var yellow_gradient = bar_ctx.createLinearGradient(0, 0, 600, 0);
yellow_gradient.addColorStop(0, 'rgb(255, 191, 0)');
yellow_gradient.addColorStop(1, 'rgb(255,255,0)');
var red_gradient = bar_ctx.createLinearGradient(0, 0, 600, 0);
red_gradient.addColorStop(0, 'rgb(210, 34, 45)');
red_gradient.addColorStop(1, 'rgb(255,0,0)');

// Chart
$(document).ready(function() {
  //cameraSetup();
  
  var options = {
    legend: false,
    responsive: true,
    maintainAspectRatio: false,
    onClick: graphClickEvent,
    scales: {
      xAxes: [
        {
          gridLines: { 
            display: false,
            color: "#ffffff" },
          ticks: {
            beginAtZero: true,
            fontColor:'#ffffff',
            steps: 10,
            stepValue: 5,
            max: 100,
            min: 5
          }
        }
      ],
      yAxes: [
        {
          gridLines: { 
            display: false,
            color: "#ffffff" 
          },
          ticks: {
            fontColor: "#ffffff"
          }
        }
      ]
    }
  };
  chart = new Chart($("#canvas1"), {
    type: "horizontalBar",
    tooltipFillColor: "rgba(51, 51, 51, 0.55)",
    scaleFontColor: "#FFFFFF",
    data: {
      labels: [res1, res2, res3],
      datasets: [
        {
          data: [70, 20, 10],
          backgroundColor: [green_gradient, yellow_gradient, red_gradient],
          hoverBackgroundColor: ["#49A9EA", "#49A9EA", "#49A9EA"]
        }
      ]
    },
    options: options
  });
});

// End Chart

//called when you click on the bars in the graph
function graphClickEvent(e) {
  //clicked element
  var element = this.getElementAtEvent(e);
  console.log(element);
  //clicked label
  var currentLabel = element[0]._model.label;
  
  var wikipediaLink = "https://en.wikipedia.org/wiki/" + currentLabel;
  // changes only the color of the active object
  //this.active[0]._chart.config.data.datasets[0].backgroundColor = "red";

  if (element.length > 0) {
  
    freeze();
    Swal.fire({
      title: currentLabel, 
      html: "Read about it ➡ <a href='" + wikipediaLink + "' target='_blank' title='Wikipedia article for " + currentLabel +"'><img class='wikiLink' height='30px' src='https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg'/></a>",  
      confirmButtonText: "<u>Back</u>",
      preConfirm: () => {unfreeze()}
});

  }
}


//called when top one gets over 90%
//gets weird because it continuously calls it if it stays over 90
function topResultOver90() {
  
  upper90 = true;
  //top label
  var currentLabel = res1;
  
  var wikipediaLink = "https://en.wikipedia.org/wiki/" + currentLabel;
  // changes only the color of the active object
  //this.active[0]._chart.config.data.datasets[0].backgroundColor = "red";
  
    freeze();
    Swal.fire({
      title: currentLabel, 
      html: "<a href='" + wikipediaLink + "' target='_blank' title='Wikipedia article for " + currentLabel +"'><img class='wikiLink' height='30px' src='https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg'/></a>",  
      confirmButtonText: "<u>Back</u>",
      preConfirm: () => {unfreeze()}
});
}


function freeze(){
  freezeIt = true;
}

function unfreeze(){
  freezeIt = false;
  upper90 = false;
}



//updates values in chart
function updateChart() {
  if(upper90 == false){
  chart.data.labels = [res1, res2, res3];
  chart.data.datasets[0].data = [con1, con2, con3];
  chart.update();
  }
}


function gotResults(results, error) {
  if (error) {
    console.error("Something went dreadfully wrong!");
    console.error(error);
  } else if (upper90 == false){
    //change ready light
    document.getElementById("results").style.background = "green";
    document.getElementById("results").title = "mobilenet loaded successfully";
    document.getElementById("loadOverlay").style.display = "none";
    //top 3 labels
    res1 = results[0].label;
    res2 = results[1].label;
    res3 = results[2].label;

    res1 = res1.charAt(0).toUpperCase() + res1.slice(1);
    res2 = res2.charAt(0).toUpperCase() + res2.slice(1);
    res3 = res3.charAt(0).toUpperCase() + res3.slice(1);
    //only return stuff before first comma
    res1 = res1.split(",")[0];
    res2 = res2.split(",")[0];
    res3 = res3.split(",")[0];

    //top 3 scores
    con1 = results[0].confidence;
    con2 = results[1].confidence;
    con3 = results[2].confidence;

    //round scores to one decimal
    con1 = con1 * 100;
    con1 = Math.round(con1 * 10) / 10;
    con2 = con2 * 100;
    con2 = Math.round(con2 * 10) / 10;
    con3 = con3 * 100;
    con3 = Math.round(con3 * 10) / 10;

    //increment the number
    num++;

    //check if the top value is above 90%
    if (con1 >= 90) {
      topResultOver90();
    }

    //put new values in chart at a set interval
    if (num == 0 || num % interval == 0 && freezeIt == false) {
      updateChart();
    }

    //rerun the analyzer
    var rgb = getAverageRGB(document.getElementById('video'));
    document.body.style.backgroundColor = 'rgb('+rgb.r+','+rgb.g+','+rgb.b+')';
  }
}




//http://jsfiddle.net/xLF38/818/
//sets background to average hue in video
function getAverageRGB(imgEl) {
    
    var blockSize = 5, // only visit every 5 pixels
        defaultRGB = {r:0,g:0,b:0}, // for non-supporting envs
        canvas = document.createElement('canvas'),
        context = canvas.getContext && canvas.getContext('2d'),
        data, width, height,
        i = -4,
        length,
        rgb = {r:0,g:0,b:0},
        count = 0;
        
    if (!context) {
        return defaultRGB;
    }
    
    height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
    width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;
    
    context.drawImage(imgEl, 0, 0);
    
    try {
        data = context.getImageData(0, 0, width, height);
    } catch(e) {
        /* security error, img on diff domain */alert('x');
        return defaultRGB;
    }
    
    length = data.data.length;
    
    while ( (i += blockSize * 4) < length ) {
        ++count;
        rgb.r += data.data[i];
        rgb.g += data.data[i+1];
        rgb.b += data.data[i+2];
    }
    
    // ~~ used to floor values
    rgb.r = ~~(rgb.r/count);
    rgb.g = ~~(rgb.g/count);
    rgb.b = ~~(rgb.b/count);
    
    return rgb;
    
}
              
            
!
999px

Console