threeJScancasTexure

by denis_miroshnikov_ts

HTML

<canvas id="canvas" style=""></canvas>

JavaScript

var materials = [];
var textures = [];
var width = window.innerWidth;
var height = window.innerHeight / 2;

var size = 257;

function changeCanvas() {
    var canvas = document.getElementById('canvas');

    canvas.width = canvas.height = size;
    var context = canvas.getContext('2d');
    context.font = '20pt Arial';
    context.fillStyle = 'red';
    context.fillRect(0, 0, canvas.width, canvas.height);
    context.fillStyle = 'white';
    context.fillRect(10, 10, canvas.width - 20, canvas.height - 20);
    context.fillStyle = 'black';
    context.textAlign = "center";
    context.textBaseline = "middle";
    context.fillText(new Date().getTime(), canvas.width / 2, canvas.height / 2);

    return canvas;
}

function init() {
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(70, width / height, 0.1, 1000);
    camera.position.y = 90;
    camera.position.z = 800;
    scene.add(camera);

    for (var i = 0; i < 6; i++) {
        var texture = new THREE.Texture(changeCanvas());
        textures.push(texture);

        var material = new THREE.MeshBasicMaterial({ map: texture });
        materials.push(material);
    }

    var cube = new THREE.Mesh(new THREE.CubeGeometry(size, size, size, 1, 1, 1, materials), new THREE.MeshFaceMaterial());
    cube.position.y = 150;
    cube.rotation.y = 10;
    scene.add(cube);

    renderer = new THREE.WebGLRenderer();
    renderer.setSize(width, height);
    document.body.appendChild(renderer.domElement);
}

function animate() {
    requestAnimationFrame(animate);
    render();
}

function render() {
    changeCanvas();

    for (var i = 0; i < textures.length; i++) {
        textures[i].needsUpdate = true;
    }

    renderer.render(scene, camera);
}

init();
animate();