在正文的第一句加入“我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!”
主要是用到了three.js BufferGeometry这方法,我是在本地启动的服务,所以就不贴官网链接了,
BufferGeometry是面片、线或点几何体的有效表述。包括顶点位置,面片索引、法相量、颜色值、UV 坐标和自定义缓存属性值。使用 BufferGeometry 可以有效减少向 GPU 传输上述数据所需的开销。(官网的解释) 这是截图
主要规则就是三点创建一个平面和两点创建一条线
创建场景
const scene = new THREE.Scene();
创建相机
// 创建相机(透视相机)
const camera = new THREE.PerspectiveCamera(
75, // 摄像机角度
window.innerWidth/window.innerHeight, // 宽高比
0.1,// 最近位置
1000, // 最远位置
); //
// 相机位置
camera.position.set(0,0,10) // x y z
比较麻烦的就是创建物体 我们要创建50个三角形物体
// 创建50个物体
for(let i=0;i<50;i++) {
// 50个物体,一个面有三个点,一个点的坐标是xyz
const geometry = new THREE.BufferGeometry(); // 创建 BufferGeometry界面
const positionArray = new Float32Array(9); Float32Array类型数组需要指定长度才可以
for(let j=0;j<9;j++) { // 三个点的坐标
positionArray[j] = Math.random()*10 -5 // 0-5
}
// 设置点坐标及绘画面
geometry.setAttribute('position', new THREE.BufferAttribute( positionArray, 3 ) );
let color = new THREE.Color(Math.random(),Math.random(),Math.random()) // 随机颜色
const cun = new THREE.MeshBasicMaterial({ // 材质
color: color,
transparent: true,
opacity: 0.5
})
const cube = new THREE.Mesh(geometry,cun)
scene.add(cube);
}
渲染器
const renderer = new THREE.WebGL1Renderer();
// 设置渲染尺寸大小
renderer.setSize(window.innerWidth,window.innerHeight);
// 渲染器添加到canvas画布
document.body.appendChild(renderer.domElement) // 把body上追加
function render() {
renderer.render(scene,camera)
// 渲染下一桢
requestAnimationFrame(render)
}
render()
其实这个在three的官网也有相对应的demo,但是比我的这个复杂,这个只是简版,但是也相对简单好理解
代码块