// 实例化渲染 - 100个随机立方体,只需1个DrawCall
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0f172a);
const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 0, 30);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
scene.add(new THREE.AmbientLight(0x404040, 2));
const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(10, 10, 10);
scene.add(light);
// 实例化渲染100个立方体
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({ color: 0x3b82f6 });
const mesh = new THREE.InstancedMesh(geometry, material, 100);
const matrix = new THREE.Matrix4();
const color = new THREE.Color();
for (let i = 0; i < 100; i++) {
matrix.setPosition(
Math.random() * 40 - 20,
Math.random() * 40 - 20,
Math.random() * 40 - 20
);
mesh.setMatrixAt(i, matrix);
mesh.setColorAt(i, color.setHSL(Math.random(), 0.7, 0.5));
}
scene.add(mesh);
function animate() {
requestAnimationFrame(animate);
mesh.rotation.x += 0.002;
mesh.rotation.y += 0.003;
renderer.render(scene, camera);
}
animate();