Threejs基础
1.基础代码
var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(); var renderer = new THREE.WebGLRenderer(); var loop = function(){ requestAnimationFrame(loop); renderer.render(scene, camera); } loop(); document.body.appendChild(renderer.domElement);
2.旋转立方体(无材质)
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <title>Threejs-cube</title> <style> #container{ width: 500px; height: 300px; background-color: #f4f4f4; } </style> </head> <body> <p>ok</p> <div id="container"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/84/three.js"></script> <script src="demo-cube.js"></script> </body> </html>
demo-cube.js
//getElement var container = document.getElementById('container'); //var scene,camera,renderer var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera( 75, container.clientWidth / container.clientHeight, 0.1, 1000 ); var renderer = new THREE.WebGLRenderer(); //var geometry,mesh var geometry = new THREE.CubeGeometry(10, 10, 10); var mesh = new THREE.Mesh(geometry); //set scene,camera scene.add(mesh); camera.position.z = 20; //loop render var loop = function(){ requestAnimationFrame(loop); renderer.render(scene, camera); mesh.rotation.x += .03; mesh.rotation.y += .05; mesh.rotation.z += .01; } loop(); //append renderer dom renderer.setSize(container.clientWidth, container.clientHeight); container.appendChild(renderer.domElement);