webgl + webrtc

by alessandro_pezzato

HTML

<script src="https://github.com/mrdoob/three.js/raw/master/build/three.min.js"></script>
    <div id="tools">
        <button onclick="attachWebcam()">webcam</button>
        <button onclick="attachVideoFile()">play video file</button>
    </div>
    <div id="container"></div>
    <video id="video"></video>

CSS

* {
    font-family: sans-serif;
}

body {
    background: #cccccc;
}

#tools {
    position: absolute;
    top: 0;
    right: 0;
    background: #333333;
    color: #ffffff;
}

#video {
    display: none;
}

#container {
    background-color: #ffffff;
}

JavaScript

var texture = null;
var renderer = null;
var scene = null;
var camera = null;
var video = null;
var cube = null;
var time = null;

$(function() {
    init();
    animate();
});

function init() {
    /* renderer */
    var WIDTH = 320;
    var HEIGHT = 240;
    renderer = new THREE.WebGLRenderer();
    renderer.setSize(WIDTH, HEIGHT);
    var $container = $('#container');
    $container.append(renderer.domElement);

    /* scene */
    scene = new THREE.Scene();

    /* camera */
    var VIEW_ANGLE = 45;
    var ASPECT = WIDTH / HEIGHT;
    var NEAR = 0.1;
    var FAR = 10000;
    camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
    camera.position.z = 150;
    scene.add(camera);

    /* cube */
    cube = new THREE.Mesh(new THREE.CubeGeometry(50, 50, 50));
    scene.add(cube);

    /* light */
    var pointLight = new THREE.PointLight(0xFFFFFF);
    pointLight.position.x = 10;
    pointLight.position.y = 50;
    pointLight.position.z = 130;
    scene.add(pointLight);

    /* texture */
    video = $('#video').get(0);
    video.width = 320;
    video.height = 240;
    video.autoplay = true;
    video.style.opacity = 1;
    texture = new THREE.Texture(video);

    /* material */
    var material = new THREE.MeshLambertMaterial({
        map : texture
    });
    cube.material = material;

}

function animate() {
    requestAnimationFrame(animate);
    var now = new Date().getTime();
    var dt = now - (time || now);
    time = now;
    onFrame(dt / 1000);
    renderer.render(scene, camera);
}

function onFrame(dt) {
    cube.rotation.y += 1 * dt;
    if (video.readyState === video.HAVE_ENOUGH_DATA) {
        texture.needsUpdate = true;
    }
}

function attachVideoFile() {
    video.src = "https://github.com/mrdoob/three.js/raw/master/examples/textures/sintel.ogv";
}

function attachWebcam() {
    navigator.webkitGetUserMedia({
        audio : false,
        video : true
    }, function(stream) {
        video.src =...