Atlaslog
Atlaslog / Examples / Cesium / Model Hpr
Cesium · Runnable Example

Model Hpr

Runnable Cesium example: Model Hpr. 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-hpr.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/cesium-model-hpr.html
<!--
  示例:用航向、俯仰、横滚摆正一个长条模型
  要点:Transforms.headingPitchRollToFixedFrame 生成模型矩阵,实体模型用同一个四元数
  依赖:CesiumJS 1.121 · jsDelivr CDN,GLB 为内存生成的长方体
-->
<!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>
<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}
  input[type=range]{width:100%}
  .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>姿态角</b></div>
  <div class="row">航向 <span id="hVal">0</span>°</div>
  <div class="row"><input id="heading" type="range" min="0" max="360" step="5" value="0"></div>
  <div class="row">俯仰 <span id="pVal">0</span>°</div>
  <div class="row"><input id="pitch" type="range" min="-90" max="90" step="5" value="0"></div>
  <div class="row">横滚 <span id="rVal">0</span>°</div>
  <div class="row"><input id="roll" type="range" min="-90" max="90" step="5" value="0"></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, 400);
  var hpr = new Cesium.HeadingPitchRoll(0, 0, 0);

  /* 长方体 GLB:1.8 × 0.18 × 0.18,机头朝 +X */
  function buildBox(sx, sy, sz) {
    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 pos = [], nrm = [], idx = [];
    faces.forEach(function (f, fi) {
      f.v.forEach(function (p) {
        pos.push(p[0] * sx * 0.5, p[1] * sy * 0.5, p[2] * sz * 0.5);
        nrm.push(f.n[0], f.n[1], f.n[2]);
      });
      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),
      idx: new Uint16Array(idx),
      min: [-sx / 2, -sy / 2, -sz / 2],
      max: [sx / 2, sy / 2, sz / 2]
    };
  }

  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 = buildBox(1.8, 0.18, 0.18);

  var gltf = {
    asset: { version: '2.0' },
    scene: 0,
    scenes: [{ nodes: [0] }],
    nodes: [{ mesh: 0 }],
    meshes: [{ primitives: [{ attributes: { POSITION: 0, NORMAL: 1 }, indices: 2, material: 0 }] }],
    materials: [{
      pbrMetallicRoughness: {
        baseColorFactor: [0.55, 0.78, 1.0, 1.0],
        metallicFactor: 0.25,
        roughnessFactor: 0.35
      }
    }],
    accessors: [
      { bufferView: 0, componentType: 5126, count: 24, type: 'VEC3', min: geo.min, max: geo.max },
      { bufferView: 1, componentType: 5126, count: 24, type: 'VEC3' },
      { bufferView: 2, componentType: 5123, count: 36, type: 'SCALAR' }
    ]
  };

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

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

  Cesium.Model.fromGltfAsync({ url: url, scale: 42 }).then(function (m) {
    m.modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(CENTER, hpr);
    scene.primitives.add(m);
    model = m;
  });

  function update() {
    hpr.heading = Cesium.Math.toRadians(parseFloat(document.getElementById('heading').value));
    hpr.pitch = Cesium.Math.toRadians(parseFloat(document.getElementById('pitch').value));
    hpr.roll = Cesium.Math.toRadians(parseFloat(document.getElementById('roll').value));
    if (model) {
      model.modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(CENTER, hpr);
    }
  }

  ['heading', 'pitch', 'roll'].forEach(function (id) {
    document.getElementById(id).addEventListener('input', function () {
      document.getElementById(id === 'heading' ? 'hVal' : id === 'pitch' ? 'pVal' : 'rVal')
        .textContent = this.value;
      update();
    });
  });

  /* 地面上的北向箭头,作为航向 0 的参考 */
  viewer.entities.add({
    polyline: {
      positions: Cesium.Cartesian3.fromDegreesArray([116.389, 39.906, 116.389, 39.913]),
      width: 2,
      material: new Cesium.PolylineArrowMaterialProperty(
        Cesium.Color.fromCssColorString('#ffb13d')
      ),
      clampToGround: true
    }
  });

  viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(116.389, 39.906, 0),
    point: {
      pixelSize: 8,
      color: Cesium.Color.fromCssColorString('#ffb13d'),
      disableDepthTestDistance: Number.POSITIVE_INFINITY
    }
  });

  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(116.396, 39.900, 620),
    orientation: {
      heading: Cesium.Math.toRadians(24),
      pitch: Cesium.Math.toRadians(-14),
      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 · EXAMPLEModel Load Cesium · EXAMPLEModel Texture Glb Cesium · EXAMPLEMoon