threeJS绘制球体

使用three.js绘制球体

实现思路:
1. 生成三大组件:场景、相机、渲染器;
2. 场景添加光源;
3. 场景添加球体,并为球体添加纹理贴图;
4. 循环渲染。


首先,初始化变量,包括用到的渲染器、场景、相机、球体、以及轨道控件。

let webGLRenderer, camera, scene, sphere, orbitControls;

const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;

生成渲染器并添加到页面:

function initRenderer() {
   webGLRenderer = new THREE.WebGLRenderer({
        antialias: true,   // 抗锯齿
    });
    webGLRenderer.setSize(windowWidth, windowHeight);
    webGLRenderer.setClearColor(new THREE.Color(0x000000));  // color, alpha
    document.getElementById('canvas-frame').appendChild(webGLRenderer.domElement);
}

创建相机,聚焦到 (0, 0, 0) 位置。

function initCamera() {
    camera = new THREE.PerspectiveCamera(45, windowWidth / windowHeight, 1, 1000);  // 创建透视相机
    camera.position.z = 400;
    camera.up.y = 1;
    camera.lookAt(new THREE.Vector3(0, 0, 0));
}

创建场景:

function initScene() {
   scene = new THREE.Scene();
}

场景中添加环境光以及平行光源:

function initLight() {
   const ambiLight = new THREE.AmbientLight(0x333333);
   scene.add(ambiLight);

   const direLight = new THREE.DirectionalLight(0xffffff, 1.0);  // 平行光 DirectionalLight (光源颜色的RGB数值, 光源强度数值) 
   direLight.position.set(500, 500, 500);
   scene.add(direLight);
}

添加球体,使用TextureLoader纹理加载器加载纹理, 并使用材质的map属性设置纹理贴图:

function initObject() {
   const loader = new THREE.TextureLoader();
   loader.load("../textures/planets/earth.jpg", (texture) => {
	   const mat = new THREE.MeshLambertMaterial();
	   // const mat = new THREE.MeshPhongMaterial();
	   mat.map = texture;
	   sphere = new THREE.Mesh(new THREE.SphereGeometry(70, 60, 60), mat);
	   scene.add(sphere);
  })
}

three.js 加载模型或者是纹理图片时需要一个本地的web服务器,可使用 nodeJs 的 HTTP Server 模块启动。

  • npm install -g http-server
  • http-server

添加轨道控件:

function initOrbit() {
   orbitControls = new THREE.OrbitControls(camera, webGLRenderer.domElement);
}

循环渲染函数:

function render() {
   // 使用requestAnimationFrame按照浏览器定义时间间隔调用函数,并保证动画尽量平滑、高效
   requestAnimationFrame(render);
   // 球体自动绕Y轴旋转
   if (sphere) sphere.rotation.y += 0.01;
   // 在对摄像机的转换进行任何手动更改之后,必须调用orbitControls.update()
   orbitControls.update();
   webGLRenderer.render(scene, camera);
}

最后,所有函数按顺序定义,完成绘制:

// 初始化函数
function init() {
    // 创建 WebGLobal 渲染器
    initRenderer();
    // 生成相机
    initCamera();
    // 生成场景
    initScene();
    // 添加光源
    initLight();
    // 添加物体
    initObject();
    // 添加轨道控件
    initOrbit();
	// 渲染
    webGLRenderer.render(scene, camera);
    render();
}

最终效果:
在这里插入图片描述

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值