本文我们介绍在three.js中如何给3D场景添加背景,我们有3种方式来实现这个目的。通过html添加背景元素,这实际上一个2D背景;
在three.js加载图片并设置为scene.background,这种方法的好处是可以被后处理(post-processing)效果所影响;
在three.js中绘制天空盒作为背景。
第一种是直接在canvas的css样式中设置background(或者background-image),
然后three.js中设置渲染的alpha为true,这样就表示3D场景是透明的,不会隐藏后面的背景。
修改后结果如下:
第二种方法也很简单,代码示例如下:const loader = new THREE.TextureLoader();
const bgTexture = loader.load('/path/to/sky.jpg');
scene.background = bgTexture;
不过这种情况下,背景图片可能会被拉伸,解决方法是设置背景贴图的offset和repeat属性来绘制其中一部分:// Set the repeat and offset properties of the background texture
// to keep the image's aspect correct.
// Note the image may not have loaded yet.
const canvasAspect = canvas.clientWidth / canvas.clientHeight;
const imageAspect = bgTexture.image