当前位置:网站首页>『Three.js』辅助坐标轴

『Three.js』辅助坐标轴

2022-06-12 07:48:00 InfoQ

本文简介

点赞 + 关注 + 收藏 = 学会了



在日常开发和学习中,坐标轴能粗略的帮我们定位元素位置和关系。所以我使用 
Three.js
 学习和开发时基本都会打开坐标轴。



本文使用 
Three.js
 的版本:
137


编码

在使用坐标轴之前,我们先创建一个元素,可以让我们更容易理解坐标轴。

<style>
 body {
 margin: 0;
 }
</style>

<div id=&quot;canvasBox&quot;></div>

<script type=&quot;module&quot;>
 import {
 Scene,
 PerspectiveCamera,
 WebGLRenderer,
 BoxGeometry,
 MeshBasicMaterial,
 Mesh
 } from '../js/Three/Three.js'



 // 场景
 const scene = new Scene()

 // 相机
 const camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)

 // 渲染器
 const renderer = new WebGLRenderer()

 // 将渲染器的大小设置为窗口的大小
 renderer.setSize(window.innerWidth, window.innerHeight)

 // 将渲染器绑定到指定的DOM元素中
 document.getElementById('canvasBox').appendChild(renderer.domElement)

 // 几何体
 const geometry = new BoxGeometry()

 // 网格基础材质,设置颜色
 const material = new MeshBasicMaterial({color: 0xff2299})
 const cube = new Mesh(geometry, material)
 scene.add(cube)

 // 设置摄像机在z轴上的距离
 camera.position.x = -3
 camera.position.y = 5
 camera.position.z = 5

 // 将摄像机的方向对准场景的中心点
 camera.lookAt(scene.position)

 // 适当的旋转一下立方体
 cube.rotation.x += 0.8
 cube.rotation.y += 0.8

 // 将场景和相机添加到渲染器中并执行渲染
 renderer.render(scene, camera)
</script>

null

效果出来了。


创建坐标轴

添加坐标轴需要引入 
AxesHelper

<!-- 省略上面的 html 代码 -->
<script type=&quot;module&quot;>
 import {
 // 省略前面的引入
 AxesHelper
 } from '../js/Three/Three.js'

 // 省略部分代码...

 // 创建坐标轴
 const axes = new AxesHelper()
 // 将坐标轴添加到场景中
 scene.add(axes)

 // 将场景和相机添加到渲染器中并执行渲染
 renderer.render(scene, camera)
</script>

null


此时就可以看到坐标轴了


设置坐标轴长度

从上面的例子看,坐标轴有点短,所以在创建坐标轴的时候建议传入一个长度。

本例传个比较小的值做演示,真实项目会传50、100那样的。

const axes = new AxesHelper(2)
null

此时的坐标轴看上去就比之前长很多了。


设置坐标轴颜色

从上面的案例中可以发现,坐标轴默认的颜色是:
红、绿、蓝
。如果你希望自定义坐标轴的颜色,可以使用 
setColors
 进行修改。该方法需要传3个参数进去。

// 创建坐标轴
const axes = new AxesHelper(2)
// 设置坐标轴颜色
axes.setColors('pink', 0xf0ff00, 'rgb(60, 200, 130)')

null


如果你只传1个参数,那3条坐标轴的颜色都会相同。

如果只传2个参数,那么第3个参数的值会直接取到第2个参数的值,所以y和z轴的颜色相同。

这两种情况建议你自己手动测试,我在这里就不贴代码了~



代码仓库

Three.js 坐标轴
原网站

版权声明
本文为[InfoQ]所创,转载请带上原文链接,感谢
https://xie.infoq.cn/article/ef7890fab643ebd61241a8d90