Atlaslog
Atlaslog / Examples / three.js / Materials Canvas Texture
three.js · Runnable Example

Materials Canvas Texture

Runnable three.js example: Materials Canvas Texture. 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-materials-canvas-texture.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/three-materials-canvas-texture.html
<!--
  说明:用 canvas 现场画一张地块底图,作为贴图铺在地面上,平铺次数可调
  核心逻辑:CanvasTexture 配 RepeatWrapping,repeat 控制每块地重复几次
  依赖: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>Canvas 纹理</title>
<style>
  html,body{height:100%;margin:0;background:#0a1016}
  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: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="rv">2</b> ×</span>
  <label>repeat <input type="range" id="rep" min="1" max="8" step="1" value="2"></label>
  <button id="redraw">换一套配色</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(0x0a1016);
scene.fog = new THREE.Fog(0x0a1016, 30, 70);

const camera = new THREE.PerspectiveCamera(45, stage.clientWidth / stage.clientHeight, 0.1, 200);
camera.position.set(0, 18, 20);

const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0, 0);
controls.enableDamping = true;
controls.maxPolarAngle = Math.PI * 0.47;
controls.update();

scene.add(new THREE.HemisphereLight(0xb8d2ee, 0x101820, 1.3));
const sun = new THREE.DirectionalLight(0xffeccd, 2.0);
sun.position.set(-12, 18, 10);
scene.add(sun);

const SIZE = 512;
const cv = document.createElement('canvas');
cv.width = cv.height = SIZE;
const ctx = cv.getContext('2d');

let seed = 7;

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

/* 画一块 4 × 4 的地块拼图:道路十字、地块色块、少量建筑符号 */
function redraw() {
  ctx.fillStyle = '#1b242c';
  ctx.fillRect(0, 0, SIZE, SIZE);

  const N = 4;
  const cell = SIZE / N;

  for (let gy = 0; gy < N; gy++) {
    for (let gx = 0; gx < N; gx++) {
      const id = gy * N + gx;
      const hue = 175 + hash(id + seed) * 95;
      const light = 20 + hash(id + seed + 2) * 14;

      ctx.fillStyle = 'hsl(' + hue + ', 28%, ' + light + '%)';
      ctx.fillRect(gx * cell + 4, gy * cell + 4, cell - 8, cell - 8);

      /* 地块内的小方块,代表建筑基底 */
      const n = 2 + Math.floor(hash(id + seed + 5) * 4);
      for (let k = 0; k < n; k++) {
        const bx = gx * cell + 14 + hash(id + k + seed + 7) * (cell - 40);
        const by = gy * cell + 14 + hash(id + k + seed + 9) * (cell - 40);
        const bw = 10 + hash(id + k + seed + 11) * 22;
        ctx.fillStyle = 'rgba(200, 214, 228, ' + (0.18 + hash(k + seed) * 0.22) + ')';
        ctx.fillRect(bx, by, bw, bw * 0.7);
      }
    }
  }

  /* 道路:贯穿整张图的十字与边框,平铺后能接上 */
  ctx.strokeStyle = '#2c3a46';
  ctx.lineWidth = 8;
  for (let i = 0; i <= N; i++) {
    ctx.beginPath();
    ctx.moveTo(i * cell, 0);
    ctx.lineTo(i * cell, SIZE);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(0, i * cell);
    ctx.lineTo(SIZE, i * cell);
    ctx.stroke();
  }

  /* 中线虚线 */
  ctx.strokeStyle = 'rgba(190, 205, 220, 0.35)';
  ctx.lineWidth = 2;
  ctx.setLineDash([12, 12]);
  for (let i = 0; i <= N; i++) {
    ctx.beginPath();
    ctx.moveTo(i * cell, 0);
    ctx.lineTo(i * cell, SIZE);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(0, i * cell);
    ctx.lineTo(SIZE, i * cell);
    ctx.stroke();
  }
  ctx.setLineDash([]);
}

redraw();

const tex = new THREE.CanvasTexture(cv);
tex.colorSpace = THREE.SRGBColorSpace;
tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
tex.repeat.set(2, 2);
tex.anisotropy = renderer.capabilities.getMaxAnisotropy();

const ground = new THREE.Mesh(
  new THREE.PlaneGeometry(48, 48),
  new THREE.MeshStandardMaterial({ map: tex, roughness: 0.9, metalness: 0.03 })
);
ground.rotation.x = -Math.PI / 2;
scene.add(ground);

/* 几栋体块,让平铺的地面有尺度参照 */
function hash2(n) {
  const x = Math.sin(n * 12.7 + 4.1) * 43758.5453;
  return x - Math.floor(x);
}

for (let i = 0; i < 14; i++) {
  const w = 1.2 + hash2(i) * 2.2;
  const h = 1.5 + Math.pow(hash2(i + 3), 1.5) * 8;
  const b = new THREE.Mesh(
    new THREE.BoxGeometry(w, h, w),
    new THREE.MeshStandardMaterial({
      color: new THREE.Color().setHSL(0.55 - hash2(i + 6) * 0.1, 0.12, 0.45 + hash2(i + 8) * 0.2),
      roughness: 0.6,
      metalness: 0.15
    })
  );
  b.position.set((hash2(i + 10) - 0.5) * 34, h / 2, (hash2(i + 12) - 0.5) * 34);
  scene.add(b);
}

const repEl = document.getElementById('rep');
const rvEl = document.getElementById('rv');
repEl.addEventListener('input', function () {
  const v = Number(repEl.value);
  tex.repeat.set(v, v);
  rvEl.textContent = String(v);
});

document.getElementById('redraw').addEventListener('click', function () {
  seed = Math.random() * 1000;
  redraw();
  tex.needsUpdate = true;
});

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 · EXAMPLEMaterials Displacement three.js · EXAMPLEMath Obb three.js · EXAMPLEModel Rotate