1.定义Canvas 元素
WebGL 的渲染是需要 HTML5 Canvas 元素的。
<canvas id="mainCanvas" width="400px" height="300px"></canvas>
2.渲染器(Renderer)
1 2 3 4 5 6 7
| <script> function init(){ var renderer = new THREE.WebGLRenderer({ canvas:document.getElementById('mainCanvas') }); } </script>
|
若未定义canvas元素则
1 2 3
| var renderer = new THREE.WebGLRenderer(); renderer.setSize(400, 300); document.getElementsByTagName('body')[0].appendChild(renderer.domElement);
|
设置背景色
1
| renderer.setClearColor(0x000000);
|
3.场景(Scene)
场景相当于容器,物体都添加进场景中。
1
| var scene = new THREE.Scene();
|
4.照相机(Camera)
WebGL 和 Three.js 使用右手坐标系。
照相机也要被添加到场景中。
1 2 3
| var camera = new THREE.PerspectiveCamera(45, 4 / 3, 1, 1000); camera.position.set(0, 0, 5); scene.add(camera);
|
5.渲染
调用渲染器的渲染函数
1
| renderer.render(scene,camera);
|
6.第一节总结
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <body onload="init()"> <canvas id="mainCanvas" width="400px" height="300px"></canvas> <script> function init(){ var renderer = new THREE.WebGLRenderer({ canvas:document.getElementById('mainCanvas') }); renderer.setClearColor(0x000000); var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(45, 4 / 3, 1, 1000); camera.position.set(0, 0, 5); scene.add(camera); var cube = new THREE.Mesh(new THREE.CubeGeometry(1,2,3), new THREE.MeshBasicMaterial({ color:0xff0000 }) ); scene.add(cube); renderer.render(scene,camera); } </script> </body>
|