Atlaslog
Atlaslog / Examples / three.js / Instancing Scatter
three.js · Runnable Example

Instancing Scatter

Runnable three.js example: Instancing Scatter. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.

Open standalone → Chinese notes All three.js examples
/demos/three-instancing-scatter.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/three-instancing-scatter.html
<!--
  说明:六千棵树用同一份圆锥几何体实例化,位置按高程函数抬升,尺寸与转向随机
  核心逻辑:InstancedMesh 只上传一次几何体,矩阵里存的是每棵树的位置与缩放
  依赖: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:#0b1117}
  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:14px;align-items:center;font-size:12px;color:#8b93a1;flex-wrap:wrap}
  .bar b{color:#58a6ff;font-weight:600;font-variant-numeric:tabular-nums}
  .bar input[type=range]{width:140px;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">6000</b></span>
  <label>显示数量 <input type="range" id="density" min="500" max="6000" step="500" value="6000"></label>
  <button id="shuffle">重新分布</button>
  <span class="sp"></span>
  <span>拖拽旋转 · 滚轮缩放</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;
stage.appendChild(renderer.domElement);

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0b1117);
scene.fog = new THREE.Fog(0x0b1117, 34, 74);

const camera = new THREE.PerspectiveCamera(45, stage.clientWidth / stage.clientHeight, 0.1, 300);
camera.position.set(19, 15, 23);

const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 1.5, 0);
controls.enableDamping = true;
controls.maxPolarAngle = Math.PI * 0.49;
controls.minDistance = 6;
controls.maxDistance = 70;
controls.update();

scene.add(new THREE.HemisphereLight(0xbcd8ff, 0x18241a, 1.25));
const sun = new THREE.DirectionalLight(0xfff0d2, 2.3);
sun.position.set(-16, 24, 12);
scene.add(sun);

function heightAt(x, z) {
  const a = 1.3 * Math.sin(x * 0.3) * Math.cos(z * 0.26);
  const b = 0.6 * Math.sin(x * 0.8 + z * 0.6);
  const c = 2.6 * Math.exp(-((x - 4) * (x - 4) + (z + 4) * (z + 4)) / 34);
  return a + b + c;
}

/* 地形:与散布同源的高程函数,树根才不会悬空 */
const terrainGeo = new THREE.PlaneGeometry(36, 36, 120, 120);
terrainGeo.rotateX(-Math.PI / 2);
const tp = terrainGeo.attributes.position;
const tcolors = new Float32Array(tp.count * 3);
const tc = new THREE.Color();
let minH = Infinity;
let maxH = -Infinity;

for (let i = 0; i < tp.count; i++) {
  const h = heightAt(tp.getX(i), tp.getZ(i));
  tp.setY(i, h);
  minH = Math.min(minH, h);
  maxH = Math.max(maxH, h);
}
for (let i = 0; i < tp.count; i++) {
  const t = (tp.getY(i) - minH) / (maxH - minH);
  tc.setHSL(0.32 - 0.12 * t, 0.24, 0.18 + 0.16 * t);
  tcolors[i * 3] = tc.r;
  tcolors[i * 3 + 1] = tc.g;
  tcolors[i * 3 + 2] = tc.b;
}
terrainGeo.setAttribute('color', new THREE.BufferAttribute(tcolors, 3));
terrainGeo.computeVertexNormals();

const terrain = new THREE.Mesh(
  terrainGeo,
  new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.95 })
);
scene.add(terrain);

/* 树:一个三层圆锥合并的感觉,用单个圆锥 + 圆柱底座近似 */
const crown = new THREE.ConeGeometry(0.42, 1.5, 7);
crown.translate(0, 0.95, 0);
const treeMat = new THREE.MeshStandardMaterial({ roughness: 0.8, metalness: 0.02 });

const MAX = 6000;
const trees = new THREE.InstancedMesh(crown, treeMat, MAX);
trees.instanceMatrix.setUsage(THREE.StaticDrawUsage);
scene.add(trees);

const dummy = new THREE.Object3D();
const color = new THREE.Color();

function hash(n) {
  const x = Math.sin(n * 12.9898 + 78.233) * 43758.5453;
  return x - Math.floor(x);
}

function layout(seedOffset) {
  for (let i = 0; i < MAX; i++) {
    /* 极坐标散布,中心密、边缘疏,模拟林地边缘 */
    const a = hash(i + seedOffset) * Math.PI * 2;
    const r = Math.pow(hash(i + seedOffset + 0.31), 0.62) * 16.2;
    const x = Math.cos(a) * r;
    const z = Math.sin(a) * r;
    const y = heightAt(x, z);

    const s = 0.65 + hash(i + seedOffset + 0.77) * 1.15;
    dummy.position.set(x, y, z);
    dummy.rotation.set(0, hash(i + 5.1) * Math.PI * 2, 0);
    dummy.scale.set(s, s * (0.85 + hash(i + 2.3) * 0.5), s);
    dummy.updateMatrix();
    trees.setMatrixAt(i, dummy.matrix);

    color.setHSL(0.3 - hash(i + 9.7) * 0.06, 0.38, 0.22 + hash(i + 4.2) * 0.16);
    trees.setColorAt(i, color);
  }
  trees.instanceMatrix.needsUpdate = true;
  trees.instanceColor.needsUpdate = true;
}

layout(0);

const densityEl = document.getElementById('density');
densityEl.addEventListener('input', function () {
  const n = Number(densityEl.value);
  trees.count = n;
  document.getElementById('cnt').textContent = n.toLocaleString('en-US');
});

document.getElementById('shuffle').addEventListener('click', function () {
  layout(Math.random() * 1000);
});

renderer.setAnimationLoop(function () {
  controls.update();
  renderer.render(scene, camera);
});

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.

More three.js examples

three.js · EXAMPLEInteractive Lines three.js · EXAMPLEInteractive Points three.js · EXAMPLELights