three.js 四要素:渲染器、场景、相机、物体
其中相机和物体需要添加仅场景,渲染器通过场景和相机产生画面。
物体又是由几何体和材质组成
其中渲染器为网页中的canvas元素,其可以在网页中显示指定,也可以通过指定div容器,然后再将渲染器生成的canvas元素添加进去。两种方式分别如下:
1、指定cavas
<canvas id="mainCanvas" width="400px" height="300px" ></canvas>
var renderer = new THREE.WebGLRenderer({ canvas: document.getElementById(‘mainCanvas‘) }); renderer.setClearColor(0x000000); // black
可以在canvas 声明时设置大小,也可以通过渲染器对象设置大小
2、容器添加方式
<div id="container"></div>
var container = document.getElementById("container"); renderer = new THREE.WebGLRenderer(); renderer.setSize(width, height); container.appendChild(renderer.domElement);
这样,会将渲染器创建的canvas对象插入div容器
3、一般应用的通用架构(添加容器式)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="three.js"></script> <script> document.addEventListener("DOMContentLoaded",function(){ var width = 800, height = 600; var container = document.getElementById("container"); var scene,renderer,camera; scene = new THREE.Scene(); renderer = new THREE.WebGLRenderer(); renderer.setSize(width, height); container.appendChild(renderer.domElement); camera = new THREE.OrthographicCamera(-width / 2, width / 2, height / 2, -height / 2, 0.1, 10); //camera.position.z = 1; camera.position.set(0, 0, 1); //camera.lookAt(new THREE.Vector3(0, 0, 0)); scene.add(camera); var geometry = new THREE.PlaneBufferGeometry(300,300); var material = new THREE.MeshBasicMaterial({ //color:0xffffff }); var plane = new THREE.Mesh(geometry, material); scene.add(plane); renderer.render(scene, camera); }); </script> </head> <body> <div id="container"></div> </body> </html>
时间: 2024-10-12 15:10:01