three.js绘制有阴影的正方体
时间: 2023-11-07 09:22:44 浏览: 129
要在three.js中绘制具有阴影的正方体,你需要使用阴影映射(Shadow Mapping)技术。下面是一段示例代码:
```javascript
// 创建场景
var scene = new THREE.Scene();
// 创建相机
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
// 创建光源
var light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(0, 1, 1);
light.castShadow = true;
scene.add(light);
// 创建几何体
var geometry = new THREE.BoxGeometry(1, 1, 1);
// 创建材质
var material = new THREE.MeshStandardMaterial({color: 0xffffff});
// 创建网格
var cube = new THREE.Mesh(geometry, material);
cube.castShadow = true;
cube.receiveShadow = true;
// 将网格添加到场景中
scene.add(cube);
// 创建地面
var groundGeometry = new THREE.PlaneGeometry(10, 10);
var groundMaterial = new THREE.MeshStandardMaterial({color: 0xaaaaaa});
var ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -1;
ground.receiveShadow = true;
scene.add(ground);
// 创建渲染器
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.appendChild(renderer.domElement);
// 渲染场景
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
```
这段代码将会创建一个具有阴影的白色正方体,并在屏幕上旋转它。需要注意的是,要让物体产生阴影,你需要将`castShadow`属性设置为`true`,同时要让物体接收阴影,你需要将`receiveShadow`属性设置为`true`。而要让地面接收阴影,你只需要将其`receiveShadow`属性设置为`true`。此外,还需要通过设置`renderer.shadowMap.enabled`属性为`true`来启用阴影映射。
阅读全文