Atlaslog
Atlaslog / Examples / Cesium / Model Texture Glb
Cesium · Runnable Example

Model Texture Glb

Runnable Cesium example: Model Texture Glb. 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 Cesium examples
/demos/cesium-model-texture-glb.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/cesium-model-texture-glb.html
<!--
  示例:把 canvas 画的贴图写进 GLB
  要点:canvas 转 PNG 字节塞进 bufferView,再声明 image、texture 与 TEXCOORD_0
  依赖:CesiumJS 1.121 · jsDelivr CDN,模型与贴图都在页面内生成
-->
<!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>内嵌贴图 GLB</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/cesium@1.121.0/Build/Cesium/Widgets/widgets.css">
<style>
  html,body{height:100%;margin:0}
  body{background:#0e1116;color:#e6e8ec;overflow:hidden;
       font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif}
  #c{height:100%}
  .hud{position:absolute;left:12px;top:12px;z-index:5;background:rgba(23,28,35,.9);
       border:1px solid #2a313b;border-radius:6px;padding:9px 12px;font-size:12px;
       color:#a2a9b6;max-width:250px}
  .hud b{color:#e6e8ec;font-weight:600}
  .hud .row{margin-top:6px}
  .hud button{font:inherit;font-size:12px;padding:3px 9px;border-radius:4px;cursor:pointer;
       border:1px solid #343b46;background:#1d232b;color:#cfd6e2}
  .cesium-viewer-bottom .cesium-widget-credits,.cesium-viewer-animationContainer,
  .cesium-viewer-timelineContainer{display:none!important}
</style>
</head>
<body>
<div id="c"></div>
<div class="hud">
  <div><b>贴图 GLB</b></div>
  <div class="row" id="info">正在解析 GLB…</div>
  <div class="row"><button id="spin">旋转 90°</button></div>
  <div class="row">2048 字节级别的 PNG 内嵌在二进制块里</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/cesium@1.121.0/Build/Cesium/Cesium.js"></script>
<script>
(function () {
  'use strict';

  var viewer = new Cesium.Viewer('c', {
    baseLayer: false,
    baseLayerPicker: false, geocoder: false, homeButton: false,
    sceneModePicker: false, navigationHelpButton: false,
    animation: false, timeline: false, fullscreenButton: false,
    infoBox: false, selectionIndicator: false
  });

  var scene = viewer.scene;
  scene.globe.baseColor = Cesium.Color.fromCssColorString('#1c2733');
  scene.backgroundColor = Cesium.Color.fromCssColorString('#0e1116');
  scene.skyBox.show = false;
  scene.sun.show = false;
  scene.moon.show = false;
  if (scene.skyAtmosphere) scene.skyAtmosphere.show = false;

  var CENTER = Cesium.Cartesian3.fromDegrees(116.389, 39.906, 380);

  /* ---------- 贴图:红蓝分区 + 网格 + 中心编号 ---------- */
  function drawTexture() {
    var c = document.createElement('canvas');
    c.width = c.height = 512;
    var ctx = c.getContext('2d');

    ctx.fillStyle = '#1a2330';
    ctx.fillRect(0, 0, 512, 512);

    ctx.fillStyle = 'rgba(77,155,255,0.9)';
    ctx.fillRect(0, 0, 256, 512);
    ctx.fillStyle = 'rgba(255,177,61,0.9)';
    ctx.fillRect(256, 0, 256, 512);

    ctx.strokeStyle = 'rgba(255,255,255,0.55)';
    ctx.lineWidth = 4;
    for (var i = 0; i <= 512; i += 64) {
      ctx.beginPath(); ctx.moveTo(i, 0); ctx.lineTo(i, 512); ctx.stroke();
      ctx.beginPath(); ctx.moveTo(0, i); ctx.lineTo(512, i); ctx.stroke();
    }

    ctx.fillStyle = '#ffffff';
    ctx.font = '700 120px "Microsoft YaHei", sans-serif';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText('F1', 256, 256);

    return c.toDataURL('image/png');
  }

  function pngBytes(dataUrl) {
    var base64 = dataUrl.split(',')[1];
    var raw = atob(base64);
    var bytes = new Uint8Array(raw.length);
    for (var i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);
    return bytes;
  }

  /* ---------- 带 UV 的立方体 ---------- */
  function buildCube() {
    var faces = [
      { n: [0, 0, 1],  v: [[-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]] },
      { n: [0, 0, -1], v: [[1, -1, -1], [-1, -1, -1], [-1, 1, -1], [1, 1, -1]] },
      { n: [1, 0, 0],  v: [[1, -1, 1], [1, -1, -1], [1, 1, -1], [1, 1, 1]] },
      { n: [-1, 0, 0], v: [[-1, -1, -1], [-1, -1, 1], [-1, 1, 1], [-1, 1, -1]] },
      { n: [0, 1, 0],  v: [[-1, 1, 1], [1, 1, 1], [1, 1, -1], [-1, 1, -1]] },
      { n: [0, -1, 0], v: [[-1, -1, -1], [1, -1, -1], [1, -1, 1], [-1, -1, 1]] }
    ];
    var uv = [[0, 1], [1, 1], [1, 0], [0, 0]];
    var pos = [], nrm = [], tex = [], idx = [];
    faces.forEach(function (f, fi) {
      f.v.forEach(function (p, vi) {
        pos.push(p[0] * 0.5, p[1] * 0.5, p[2] * 0.5);
        nrm.push(f.n[0], f.n[1], f.n[2]);
        tex.push(uv[vi][0], uv[vi][1]);
      });
      var b = fi * 4;
      idx.push(b, b + 1, b + 2, b, b + 2, b + 3);
    });
    return {
      pos: new Float32Array(pos),
      nrm: new Float32Array(nrm),
      uv: new Float32Array(tex),
      idx: new Uint16Array(idx)
    };
  }

  /* ---------- 组装 GLB ---------- */
  function buildGlb(gltf, chunks) {
    var len = 0;
    chunks.forEach(function (c) { len += c.data.byteLength; });
    var bin = new Uint8Array(len);
    var offset = 0;
    gltf.bufferViews = chunks.map(function (c) {
      var view = { buffer: 0, byteOffset: offset, byteLength: c.data.byteLength };
      if (c.target) view.target = c.target;
      bin.set(new Uint8Array(c.data.buffer, c.data.byteOffset, c.data.byteLength), offset);
      offset += c.data.byteLength;
      return view;
    });
    gltf.buffers = [{ byteLength: len }];

    var json = new TextEncoder().encode(JSON.stringify(gltf));
    var jsonPad = (4 - json.length % 4) % 4;
    var binPad = (4 - len % 4) % 4;
    var total = 12 + 8 + json.length + jsonPad + 8 + len + binPad;
    var out = new Uint8Array(total);
    var dv = new DataView(out.buffer);
    dv.setUint32(0, 0x46546C67, true);
    dv.setUint32(4, 2, true);
    dv.setUint32(8, total, true);
    dv.setUint32(12, json.length + jsonPad, true);
    dv.setUint32(16, 0x4E4F534A, true);
    out.set(json, 20);
    for (var i = 0; i < jsonPad; i++) out[20 + json.length + i] = 0x20;
    var p = 20 + json.length + jsonPad;
    dv.setUint32(p, len + binPad, true);
    dv.setUint32(p + 4, 0x004E4942, true);
    out.set(bin, p + 8);
    return out;
  }

  var geo = buildCube();
  var png = pngBytes(drawTexture());

  var gltf = {
    asset: { version: '2.0' },
    scene: 0,
    scenes: [{ nodes: [0] }],
    nodes: [{ mesh: 0 }],
    meshes: [{
      primitives: [{
        attributes: { POSITION: 0, NORMAL: 1, TEXCOORD_0: 2 },
        indices: 3,
        material: 0
      }]
    }],
    images: [{ bufferView: 4, mimeType: 'image/png' }],
    samplers: [{
      magFilter: 9729, minFilter: 9729,
      wrapS: 10497, wrapT: 10497
    }],
    textures: [{ sampler: 0, source: 0 }],
    materials: [{
      pbrMetallicRoughness: {
        baseColorTexture: { index: 0 },
        metallicFactor: 0.1,
        roughnessFactor: 0.7
      }
    }],
    accessors: [
      { bufferView: 0, componentType: 5126, count: 24, type: 'VEC3',
        min: [-0.5, -0.5, -0.5], max: [0.5, 0.5, 0.5] },
      { bufferView: 1, componentType: 5126, count: 24, type: 'VEC3' },
      { bufferView: 2, componentType: 5126, count: 24, type: 'VEC2' },
      { bufferView: 3, componentType: 5123, count: 36, type: 'SCALAR' }
    ]
  };

  var glb = buildGlb(gltf, [
    { data: geo.pos, target: 34962 },
    { data: geo.nrm, target: 34962 },
    { data: geo.uv, target: 34962 },
    { data: geo.idx, target: 34963 },
    { data: png }
  ]);

  var url = URL.createObjectURL(new Blob([glb], { type: 'model/gltf-binary' }));
  var model = null;

  Cesium.Model.fromGltfAsync({ url: url, scale: 220 }).then(function (m) {
    m.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(CENTER);
    scene.primitives.add(m);
    model = m;
    document.getElementById('info').textContent =
      'PNG ' + png.length + ' 字节 · 24 个 UV 顶点';
  }).catch(function (err) {
    document.getElementById('info').textContent = '解析失败:' + err.message;
  });

  /* 地面方块,交代模型尺寸 */
  viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(116.389, 39.906, 0),
    box: {
      dimensions: new Cesium.Cartesian3(260, 260, 8),
      material: Cesium.Color.fromCssColorString('#243140')
    }
  });

  var turned = false;
  document.getElementById('spin').addEventListener('click', function () {
    turned = !turned;
    var hpr = new Cesium.HeadingPitchRoll(turned ? Math.PI / 2 : 0, 0, 0);
    CENTER = Cesium.Cartesian3.fromDegrees(116.389, 39.906, 380);
    if (model) {
      model.modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(CENTER, hpr);
    }
    this.textContent = turned ? '转回 0°' : '旋转 90°';
  });

  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(116.383, 39.900, 950),
    orientation: {
      heading: Cesium.Math.toRadians(24),
      pitch: Cesium.Math.toRadians(-16),
      roll: 0
    },
    duration: 0
  });
})();
</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 Cesium examples

Cesium · EXAMPLEMoon Cesium · EXAMPLEMouse Pick Cesium · EXAMPLEMsaa