Three.js教程:threejs语法总结

推荐:将 NSDT场景编辑器 加入你的3D工具链
其他系列工具: NSDT简石数字孪生

threejs语法总结

本节课从JavaScript面向对象语法的角度,给大家总结下threejs API的使用习惯,这样方便大家更好的使用threejs API。

Three.js语法总结:类(构造函数)

Three.js提供了各种各样的类(构造函数),通过new关键字可以实例化类(构造函数),获得一个对象,对象具有属性和方法。

// new实例化类THREE.MeshLambertMaterial,创建一个材质对象
const material = new THREE.MeshLambertMaterial();
// 可以看到材质对象的属性color、side、opacity、transparent...
// 通过属性可以看到threejs默认的属性值
console.log('查看材质对象',material);
// 查看材质默认属性值
console.log('material.color',material.color);
console.log('material.side',material.side);
console.log('material.transparent',material.transparent);
console.log('material.opacity',material.opacity);

类(构造函数)的参数设置属性

通过类(构造函数)的参数设置属性

const material = new THREE.MeshLambertMaterial({
    color: 0x00ffff, 
    side:THREE.DoubleSide,
    transparent:true,
    opacity:0.5,
});

查看选项参数设置的材质属性值,可以和原来默认属性值对比

console.log('material.color',material.color);
console.log('material.side',material.side);
console.log('material.transparent',material.transparent);
console.log('material.opacity',material.opacity);

访问对象属性改变属性的值

// 访问对象属性改变属性的值
material.transparent = false;
material.opacity = 1.0;
console.log('directionalLight',ambient.intensity);
directionalLight.intensity = 0.1;//改变光源强度

父类和子类

如果你学习过JavaScript面向对象,应该有父类和子类的概念,子类是通过父类派生出来的,会继承父类的属性或方法。

  • 环境光、平行光源的父类Light
  • mesh、light光源的父类Object3D

如果你想通过文档查询一个类的方法或属性,除了可以查询类本身,还可以查询类的父类。

通过对象的方法改变对象的属性

console.log('模型位置属性',mesh.position);
mesh.position.x = 50;//访问属性改变位置x坐标
mesh.translateX(50);//执行方法改变位置属性

3D建模学习工作室

上一篇:Three.js教程:gui.js库(分组) (mvrlink.com)

下一篇:Three.js教程:几何体顶点位置数据和点模型 (mvrlink.com)

猜你喜欢

转载自blog.csdn.net/ygtu2018/article/details/131470154