Three.js Mouse drag Rotate Cube (3D WebGL)
by bizamajig
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r70/three.js"></script>
<div>Click and Drag to Rotate the Cube</div>
CSS
html, body
{
margin: 0;
padding: 0;
}
JavaScript
var three = THREE;
var scene = new three.Scene();
var camera = new three.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
var renderer = new three.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var geometry = new three.BoxGeometry(1, 1, 1);
//var material = new three.MeshNormalMaterial();
/* * /
var material = new three.MeshBasicMaterial({
color: 0x00ff00
});
/* */
/* */
three.ImageUtils.crossOrigin = '';
var texture = three.ImageUtils.loadTexture('http://i.imgur.com/CEGihbB.gif');
texture.anisotropy = renderer.getMaxAnisotropy();
var material = new three.MeshFaceMaterial([
new three.MeshBasicMaterial({
color: 0x00ff00
}),
new three.MeshBasicMaterial({
color: 0xff0000
}),
new three.MeshBasicMaterial({
//color: 0x0000ff,
map: texture
}),
new three.MeshBasicMaterial({
color: 0xffff00
}),
new three.MeshBasicMaterial({
color: 0x00ffff
}),
new three.MeshBasicMaterial({
color: 0xff00ff
})
]);
/* */
var cube = new three.Mesh(geometry, material);
cube.rotation.x = Math.PI/4;
cube.rotation.y = Math.PI/4;
scene.add(cube);
camera.position.z = 5;
/* */
var isDragging = false;
var previousMousePosition = {
x: 0,
y: 0
};
$(renderer.domElement).on('mousedown', function(e) {
isDragging = true;
})
.on('mousemove', function(e) {
//console.log(e);
var deltaMove = {
x: e.offsetX-previousMousePosition.x,
y: e.offsetY-previousMousePosition.y
};
if(isDragging) {
var deltaRotationQuaternion = new three.Quaternion()
.setFromEuler(new three.Euler(
toRadians(deltaMove.y * 1),
toRadians(deltaMove.x * 1),
0,
'XYZ'
));
cube.quaternion.multiplyQuaternions(deltaRotationQuaternion, cube.quaternion);
}
...