前回の記事のindex.htmlに新規部分を追加した以下のmain.jsを読みこませる。
window.onload = function() {
// Canvas size
var width = 640;
var height = 480;
// Cube Size
var geometry = new THREE.CubeGeometry(100, 100, 100);
// Cube Material Info(not metal)
var texture = new THREE.ImageUtils.loadTexture('./img/tex.jpg');
var material = new THREE.MeshLambertMaterial({map: texture});
// Create Cube
var mesh = new THREE.Mesh(geometry, material);
// Rotate Cube
mesh.rotation = {x: 0.5, y: 0.5, z: 0.0};
// Setting Camera
var camera = new THREE.PerspectiveCamera(40, width / height, 1, 1000);
// Camera Position
camera.position.z = -400;
// Camera Angle
camera.lookAt(mesh.position);
// Create Space
var scene = new THREE.Scene();
// Add cube to Space
scene.add(mesh);
// Create Light element
var light = new THREE.DirectionalLight(0xffffff, 1.5);
// Light element position
light.position = {x: 0, y: 0.2, z: -1};
// Add light element to the space
scene.add(light);
// Create renderer
var renderer = new THREE.WebGLRenderer();
// Set canvas size
renderer.setSize(width, height);
// Set canvas to div element
document.getElementById('canvas').appendChild(renderer.domElement);
var mousedown = false;
renderer.domElement.addEventListener('mousedown', function(e) {
mousedown = true;
prevPosition = {x: e.pageX, y: e.pageY};
}, false);
renderer.domElement.addEventListener('mousemove', function(e) {
if (!mousedown) return;
moveDistance = {x: prevPosition.x - e.pageX, y: prevPosition.y - e.pageY};
mesh.rotation.x += moveDistance.y * 0.01;
mesh.rotation.y -= moveDistance.x * 0.01;
prevPosition = {x: e.pageX, y: e.pageY};
render();
}, false);
renderer.domElement.addEventListener('mouseup', function(e) {
mousedown = false;
}, false);
function render(){
renderer.render(scene, camera);
}
}
結果は次のようになる。ドラッグで立方体が回転する。
Three.js面白いな。何か作ってみよう。