three.js實現的3D球狀拖動旋轉效果

admin發表於2017-04-17

分享一段程式碼例項,它利用three.js實現了3D球狀元素的旋轉效果。

預設狀態下可以自動旋轉,也可以利用滑鼠拖動旋轉。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
* {
  padding: 0;
  margin: 0;
}
</style>
<script src="https://cdn.bootcss.com/three.js/r81/three.js"></script>
</head>
<body>
<script type="text/javascript">
var scene,
  camera,
  renderer;
 
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
renderer = new THREE.WebGLRenderer();
 
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
 
scene.add(camera);
 
camera.position.z = 600;
 
var radius = 3,
  segemnt = 20,
  rings = 20,
  R = 300;
 
var group = new THREE.Group();
var bows = new THREE.Group();
 
var sphereMaterial = new THREE.MeshLambertMaterial({
  color: 0xff0000
});
 
for (var i = 0; i < 19; i++) {
  var ball = new THREE.Mesh(new THREE.SphereGeometry(radius, segemnt, rings), sphereMaterial);
  ball.position.x = R * Math.sin((Math.PI / 18) * i);
  ball.position.y = R * Math.cos((Math.PI / 18) * i);
 
  group.add(ball);
}
for (var j = 0; j < 36; j++) {
  var bow = group.clone();
  bow.rotation.y = Math.PI * 2 / 36 * j;
  bows.add(bow);
}
scene.add(bows);
 
 
var pointLight = new THREE.PointLight(0Xffffff);
 
pointLight.position.x = 0;
pointLight.position.y = 0;
pointLight.position.z = 1000;
 
scene.add(pointLight);
 
var mouseX, mouseY, isMove = false;
animation();
 
function animation() {
  if (!isMove) {
    requestAnimationFrame(animation);
    bows.rotation.y += Math.PI * 0.001;
    bows.rotation.x += Math.PI * 0.001;
    render();
  }
}
 
function render() {
  renderer.render(scene, camera);
}
 
document.onmousedown = function(e) {
  isMove = true;
  mouseX = e.pageX;
  mouseY = e.pageY;
};
document.onmousemove = function(e) {
  if (isMove) {
    var x = e.pageX;
    var y = e.pageY;
    var _x = x - mouseX;
    var _y = y - mouseY;
    bows.rotation.x += _y * 0.001 * Math.PI;
    bows.rotation.y += _x * 0.001 * Math.PI;
    render();
    mouseX = x;
    mouseY = y;
  }
};
document.onmouseup = function() {
  isMove = false;
  animation();
}
</script>
</body>
</html>

相關文章