Instancing
Runnable three.js example: Instancing. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.
single HTML file · CDN dependencies onlyinterface may contain Chinese labels
Source
<!--
说明:用 InstancedMesh 一次绘制数千栋楼,并与逐个 Mesh 的方式对比绘制调用与帧率
核心逻辑:同一个几何体加逐实例矩阵与颜色,一个 draw call 完成全部实例
依赖:three.js 0.160.0、OrbitControls · jsDelivr CDN(ESM + importmap)
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>实例化渲染</title>
<style>
html,body{height:100%;margin:0;background:#0d1117}
body{display:flex;flex-direction:column;overflow:hidden;
font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif;color:#e6e8ec}
.bar{flex:0 0 auto;padding:8px 12px;background:#161b22;border-bottom:1px solid #252c36;
display:flex;gap:12px;align-items:center;font-size:12px;color:#8b93a1;flex-wrap:wrap}
.bar b{color:#58a6ff;font-weight:600}
.bar input[type=range]{width:130px;accent-color:#4f9ef8}
.bar button{font:inherit;font-size:12px;padding:4px 10px;border-radius:5px;cursor:pointer;
border:1px solid #303845;background:#1d2531;color:#c8d2e0}
.bar button:hover{background:#253040}
.bar .sp{flex:1 1 auto}
#stage{flex:1 1 auto;min-height:0;position:relative}
#stage canvas{display:block}
</style>
</head>
<body>
<div class="bar">
<span>实例数 <b id="cnt">2400</b></span>
<label>数量 <input type="range" id="count" min="400" max="4000" step="200" value="2400"></label>
<button id="mode">切到独立 Mesh</button>
<span class="sp"></span>
<span>FPS <b id="fps">--</b></span>
<span>draw call <b id="calls">--</b></span>
</div>
<div id="stage"></div>
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
const stage = document.getElementById('stage');
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(stage.clientWidth, stage.clientHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0b1016);
scene.fog = new THREE.Fog(0x0b1016, 60, 190);
const camera = new THREE.PerspectiveCamera(
45, stage.clientWidth / stage.clientHeight, 0.5, 400
);
camera.position.set(52, 42, 58);
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 6, 0);
controls.enableDamping = true;
controls.minDistance = 25;
controls.maxDistance = 180;
controls.maxPolarAngle = Math.PI * 0.49;
controls.update();
scene.add(new THREE.HemisphereLight(0xbcd8ff, 0x16202a, 1.2));
const sun = new THREE.DirectionalLight(0xfff0d8, 2.2);
sun.position.set(-40, 60, 30);
scene.add(sun);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(220, 220),
new THREE.MeshStandardMaterial({ color: 0x141c24, roughness: 1 })
);
ground.rotation.x = -Math.PI / 2;
scene.add(ground);
/* 所有实例共用一个几何体与一个材质 */
const boxGeo = new THREE.BoxGeometry(1.4, 1, 1.4);
boxGeo.translate(0, 0.5, 0); // 让原点落在楼底,缩放时不会陷入地面
const boxMat = new THREE.MeshStandardMaterial({
roughness: 0.72,
metalness: 0.08,
vertexColors: false
});
let group = null;
let mode = 'instanced';
let count = 2400;
const dummy = new THREE.Object3D();
const tint = new THREE.Color();
/* 用固定种子生成布局,切换模式时位置保持一致 */
function layout(i) {
const a = i * 2.39996; // 黄金角,散点分布均匀
const r = 6 + Math.sqrt(i) * 2.1;
const h = 3 + ((i * 37) % 23) * 1.35;
return {
x: Math.cos(a) * r,
z: Math.sin(a) * r,
h: h,
rot: ((i * 53) % 90) * Math.PI / 180
};
}
function disposeGroup(node) {
if (!node) return;
node.traverse(function (obj) {
if (obj.isMesh && obj.material !== boxMat) obj.material.dispose();
if (obj.isInstancedMesh) obj.dispose();
});
scene.remove(node);
}
function build() {
disposeGroup(group);
group = new THREE.Group();
if (mode === 'instanced') {
const mesh = new THREE.InstancedMesh(boxGeo, boxMat, count);
mesh.instanceMatrix.setUsage(THREE.StaticDrawUsage);
for (let i = 0; i < count; i++) {
const p = layout(i);
dummy.position.set(p.x, 0, p.z);
dummy.rotation.set(0, p.rot, 0);
dummy.scale.set(1, p.h, 1);
dummy.updateMatrix();
mesh.setMatrixAt(i, dummy.matrix);
tint.setHSL(0.56 + (p.h / 60) * 0.1, 0.35, 0.28 + (p.h / 60) * 0.3);
mesh.setColorAt(i, tint);
}
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
mesh.frustumCulled = false; // 实例分布很广,包围球判断会误裁
group.add(mesh);
} else {
for (let i = 0; i < count; i++) {
const p = layout(i);
const mesh = new THREE.Mesh(boxGeo, boxMat);
mesh.position.set(p.x, 0, p.z);
mesh.rotation.y = p.rot;
mesh.scale.set(1, p.h, 1);
group.add(mesh);
}
}
scene.add(group);
}
build();
const cntEl = document.getElementById('cnt');
const fpsEl = document.getElementById('fps');
const callsEl = document.getElementById('calls');
const modeBtn = document.getElementById('mode');
modeBtn.addEventListener('click', function () {
mode = mode === 'instanced' ? 'mesh' : 'instanced';
modeBtn.textContent = mode === 'instanced' ? '切到独立 Mesh' : '切到实例化';
build();
});
const countInput = document.getElementById('count');
countInput.addEventListener('change', function () {
count = Number(countInput.value);
cntEl.textContent = count;
build();
});
/* 每半秒统计一次帧率 */
let frames = 0;
let mark = performance.now();
renderer.setAnimationLoop(function () {
controls.update();
renderer.render(scene, camera);
frames++;
const now = performance.now();
if (now - mark >= 500) {
fpsEl.textContent = Math.round(frames * 1000 / (now - mark));
callsEl.textContent = renderer.info.render.calls;
frames = 0;
mark = now;
}
});
window.addEventListener('resize', function () {
const w = stage.clientWidth;
const h = stage.clientHeight;
camera.aspect = w / h;
camera.updateProjectionMatrix();
renderer.setSize(w, h);
});
</script>
</body>
</html>
Language: the code and this page are in English; the full tutorial and API notes for this example are in Chinese. The demo itself is the authoritative version — it runs exactly as shown.