Create a gist now

Instantly share code, notes, and snippets.

@AVGP /index.html
Last active Feb 21, 2017

Example of using Three.js, the SoftwareRenderer
<!doctype html>
<html>
<head>
<title>Isomorphic Three.js</title>
<style>
html, body {
height: 100%;
height: 100vh;
padding: 0;
margin: 0;
border: 0;
box-sizing: border-box;
}
</style>
</head>
<body>
<canvas width="500" height="500"></canvas>
<script src="app.js"></script>
</body>
</html>
var THREE = require('three'),
SoftwareRenderer = require('three-software-renderer');
var scene = new THREE.Scene(),
cam = new THREE.PerspectiveCamera(45, 1, 1, 2000);
cam.position.z = 100;
var box = new THREE.Mesh(
new THREE.BoxGeometry(30, 30, 30),
new THREE.MeshBasicMaterial({color: 0xff0000})
);
scene.add(box);
var r = new SoftwareRenderer();
r.setSize(500, 500);
// render a frame in memory
var pixels = r.render(scene, cam);
// If we're in a browser, get the canvas and the context for it
if(typeof document !== 'undefined') {
var canvas = document.querySelector('canvas');
canvas.width = 500;
canvas.height = 500;
var ctx = canvas.getContext('2d');
// render the pixel data onto the canvas
ctx.putImageData(new ImageData(pixels.data, pixels.width, pixels.height), 0, 0);
// render more frames :)
requestAnimationFrame(function render() {
box.rotation.y += Math.PI / 100;
pixels = r.render(scene, cam);
ctx.putImageData(new ImageData(pixels.data, pixels.width, pixels.height), 0, 0);
requestAnimationFrame(render);
});
}
// Count the red pixels
var redPixels = 0;
for(var i=0; i< pixels.data.length; i+=4) {
if(pixels.data[i] == 255 && pixels.data[i + 1] === 0 && pixels.data[i + 2] === 0) redPixels++;
}
console.log('red pixels: ' + redPixels + ' (' + ((redPixels / (pixels.width * pixels.height)) * 100).toFixed(2) + ' %)');
{
"name": "isomorphic-threejs-demo",
"version": "1.0.0",
"description": "Example of using Three.js, the SoftwareRenderer",
"main": "main.js",
"scripts": {
"build": "browserify main.js | uglifyjs -mc > app.js",
"dev": "watchify main.js -v -o app.js"
},
"author": "Martin Naumann <martin@geekonaut.de>",
"license": "ISC",
"devDependencies": {
"browserify": "^8.1.0",
"uglify-js": "^2.4.16",
"watchify": "^2.2.1"
},
"dependencies": {
"three": "0.71.1",
"three-software-renderer": "^1.0.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment