Friday, December 27, 2013

3D Canvas Cube - HTML5 & JavaScript

I wanted to see if it was possible to make a cube that worked pretty much anywhere(mobile/desktop) without a plugin... The answer is, YES.
If you are impatient, then just go checkout the DEMO
I've optimized the canvas to look crisp on high density screens and mobile devices. The canvas uses devicePixelRatio to attempt to use hardware pixels instead of computed pixels(i.e. the image quality of the canvas is stupid good on the iPhone4 and high density Androids).



HTML & JavaScript Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: #ffffff;
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<h1 align="center">Canvas Cube 3D</h1>
<script src="http://cdnjs.cloudflare.com/ajax/libs/three.js/r57/three.min.js"></script>
<script>

var camera, scene, renderer;
var geometry, material, mesh;

var init = function () {

renderer = new THREE.CanvasRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 500;

scene = new THREE.Scene();

geometry = new THREE.CubeGeometry( 200, 200, 200 );
material = new THREE.MeshBasicMaterial( { color: 0x000000, wireframe: true, wireframeLinewidth: 2 } );

mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );

}

var animate = function () {

requestAnimationFrame( animate );

mesh.rotation.x = Date.now() * 0.0005;
mesh.rotation.y = Date.now() * 0.001;

renderer.render( scene, camera );

}

init();
animate();

</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script src="//ajax.googleapis.com/ajax/libs/mootools/1.4.5/mootools-yui-compressed.js" type="text/javascript"></script>
</body>
</html>