threejs 画一个正方体,背景色为透明的完整代码
时间: 2023-07-25 09:41:16 浏览: 103
以下是使用Three.js绘制一个透明背景的正方体的完整代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Transparent Cube</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
</style>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/three@0.124.0/build/three.min.js"></script>
<script>
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x000000, 0);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0xffffff, opacity: 0.5, transparent: true });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```
在这个代码中,我们使用了Three.js来创建一个场景、相机、渲染器、几何体和材质。我们将材质设置为透明,并将渲染器的背景色设置为透明。最后,我们在场景中添加了一个正方体,并在每一帧更新它的旋转。
阅读全文