Atlaslog
Atlaslog / Examples / deck.gl / Business scenarios / Molecular Structure
deck.gl · Business scenario

Molecular Structure

A benzene ring carries a side chain of C, N, O and H atoms; 42 atoms take radius and color from their element, and hydrogens can be hidden or the view reduced to atoms only.

Open standalone → Chinese notes All business examples
/demos/deckgl-nongis-molecule.htmlLIVE
single HTML file · CDN dependencies onlyinterface labels are in Chinese

Business context

Molecular structure diagrams are a basic view in cheminformatics and drug design. The users are computational chemists, structural biologists and developers building molecule editors, checking connectivity, element composition and substituent placement. Data comes from atom coordinates and element types in SDF, MOL2 or PDB files. Small molecules usually have a few dozen atoms; the 42 atoms and forty-odd bonds here are a typical size for teaching and regression testing.

Coordinates from quantum chemistry or crystal structures carry unit cells and periodic boundaries, so a single molecule is extracted, translated to the origin by its centroid and multiplied by one scale factor; exactly one ratio may exist between ångströms and scene units. Cesium is bound to geographic coordinates and three.js requires hand-built sphere and cylinder geometry, whereas ScatterplotLayer draws the atoms and LineLayer the bonds, so changing a conformer only means replacing the coordinate array.

The usual misreading is to take the pixel radius for a van der Waals radius: it encodes element type only and does not grow with zoom. Bonds are inferred from distance thresholds rather than a bond table, so two heavy atoms that sit too close are joined by a bond that does not exist. Hiding hydrogens also removes their bonds, so bond counts from the two states cannot be compared as a measure of molecular complexity.

How it works

The six benzene carbons sit on a circle of radius 1.4 Å, five ring hydrogens are placed at 2.5 Å and a hydroxyl group hangs at the para position; the side chain runs from C1 along a +y zigzag for 11 heavy atoms with 1.41 Å bond lengths, and each heavy atom receives 0.95 Å hydrogens in the x–z plane according to its hydrogen count. All coordinates are multiplied by 16 and then shifted so the bounding-box center is the origin. Bonds are not hand-listed: all 861 atom pairs are tested by distance, with a 1.25 Å threshold for bonds involving hydrogen and 1.55 Å between heavy atoms, so editing the conformer or adding hydrogens never misses a bond and never links two adjacent hydrogens.

Atom radii use radiusUnits: 'pixels', 10–10.5 px for C, N and O and 5.5 px for H, so the radius stays constant under zoom and distant hydrogens do not collapse into a single pixel through perspective; bonds are 5 px wide and one shade darker than the atoms. Clearing 'show hydrogens' swaps the data for both atoms and bonds, leaving the 18-heavy-atom skeleton; the 'atoms only' button unmounts the entire LineLayer, dropping forty-odd bonds at once. Atoms and bonds share one ångström coordinate set and one scale factor, which is the easiest place to introduce an error.

SettingEffect
radiusUnits: 'pixels'Atom radius fixed in screen pixels; appearance unchanged under zoom
1.55 Å / 1.25 ÅDistance thresholds between heavy atoms and for bonds involving hydrogen
atoms onlyNo LineLayer mounted; only 42 spheres remain
show hydrogensFilters out atoms with element H and the bonds attached to them

Note. Atoms and bonds must share one coordinate set and one scale; separate multipliers push bonds off the sphere centers and make them look like broken double bonds.

Source

demos/deckgl-nongis-molecule.html
<!--
  示例:分子结构
  要点:42 个原子按元素定半径与颜色,化学键按距离阈值配对后用 LineLayer 连接
  依赖:deck.gl 9.0 · 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>分子结构</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{position:relative;z-index:5;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}
  .bar label{display:flex;align-items:center;gap:5px;cursor:pointer}
  .bar input[type=checkbox]{accent-color:#4f9ef8}
  .bar input[type=range]{width:150px;accent-color:#4f9ef8}
  .bar button{font:inherit;font-size:12px;padding:3px 10px;border-radius:4px;cursor:pointer;
       border:1px solid #2f3947;background:#1d242e;color:#c9d3e0}
  .bar button:hover{background:#26303d}
  .bar button.on{background:#2c4a7a;border-color:#4f8ad6;color:#dfe9ff}
  .bar .sep{width:1px;height:18px;background:#2a313c;margin:0 4px}
  #cv{flex:1 1 auto;min-height:0;width:100%;display:block}
</style>
</head>
<body>
<div class="bar">
  <span>原子 <b id="n">42</b> · C/N/O/H</span><span class="sep"></span>
  <button id="ball" class="on">球棍</button>
  <label><input id="showh" type="checkbox" checked>显示氢原子</label>
</div>
<canvas id="cv"></canvas>
<script src="https://cdn.jsdelivr.net/npm/deck.gl@9.0.35/dist.min.js"></script>
<script>
(function () {
  'use strict';

  if (typeof deck === 'undefined') {
    document.body.innerHTML =
      '<div style="padding:24px;color:#ff8c74">deck.gl 加载失败,请检查能否访问 cdn.jsdelivr.net</div>';
    return;
  }

  var S = 16;                       // 1 Å 映射为 16 个场景单位
  var ELEM = {
    C: { r: 10, c: [126, 148, 172] },
    N: { r: 10.5, c: [86, 142, 255] },
    O: { r: 10.5, c: [238, 94, 78] },
    H: { r: 5.5, c: [214, 222, 234] }
  };

  var atoms = [];
  function addAtom(el, x, y, z) {
    var st = ELEM[el];
    atoms.push({ el: el, p: [x * S, y * S, z * S], r: st.r, c: st.c });
  }

  var k, h, ang;
  for (k = 0; k < 6; k++) {
    ang = Math.PI / 2 + k * Math.PI / 3;
    addAtom('C', Math.cos(ang) * 1.4, Math.sin(ang) * 1.4, 0);
  }
  for (k = 1; k < 6; k++) {
    ang = Math.PI / 2 + k * Math.PI / 3;
    addAtom('H', Math.cos(ang) * 2.5, Math.sin(ang) * 2.5, 0);
  }
  addAtom('O', 0, -2.76, 0);
  addAtom('H', 0, -3.72, 0);

  var types = ['C', 'C', 'C', 'N', 'C', 'C', 'O', 'C', 'N', 'O', 'O'];
  var hcount = [2, 2, 2, 1, 2, 3, 0, 3, 1, 1, 1];
  var cx = 0, cy = 1.4, cz = 0, sign = 1;
  for (k = 0; k < types.length; k++) {
    cx += sign * 0.55;
    cy += 1.30;
    cz += k % 2 ? 0.12 : -0.12;
    sign = -sign;
    addAtom(types[k], cx, cy, cz);
    for (h = 0; h < hcount[k]; h++) {
      var ha = h * 2.094 + k * 0.7;
      addAtom('H', cx + Math.cos(ha) * 0.95, cy, cz + Math.sin(ha) * 0.95);
    }
  }

  var minX = 1e9, minY = 1e9, minZ = 1e9, maxX = -1e9, maxY = -1e9, maxZ = -1e9;
  for (k = 0; k < atoms.length; k++) {
    var p = atoms[k].p;
    if (p[0] < minX) minX = p[0];
    if (p[1] < minY) minY = p[1];
    if (p[2] < minZ) minZ = p[2];
    if (p[0] > maxX) maxX = p[0];
    if (p[1] > maxY) maxY = p[1];
    if (p[2] > maxZ) maxZ = p[2];
  }
  var ox = (minX + maxX) / 2, oy = (minY + maxY) / 2, oz = (minZ + maxZ) / 2;
  for (k = 0; k < atoms.length; k++) {
    atoms[k].p[0] -= ox;
    atoms[k].p[1] -= oy;
    atoms[k].p[2] -= oz;
  }

  var bonds = [], bondsNoH = [];
  var i, j;
  for (i = 0; i < atoms.length; i++) {
    for (j = i + 1; j < atoms.length; j++) {
      var dx = atoms[i].p[0] - atoms[j].p[0];
      var dy = atoms[i].p[1] - atoms[j].p[1];
      var dz = atoms[i].p[2] - atoms[j].p[2];
      var lim = (atoms[i].el === 'H' || atoms[j].el === 'H') ? 1.25 * S : 1.55 * S;
      if (dx * dx + dy * dy + dz * dz < lim * lim) {
        var bd = { s: atoms[i].p, t: atoms[j].p };
        bonds.push(bd);
        if (atoms[i].el !== 'H' && atoms[j].el !== 'H') bondsNoH.push(bd);
      }
    }
  }

  var atomsNoH = [];
  for (k = 0; k < atoms.length; k++) {
    if (atoms[k].el !== 'H') atomsNoH.push(atoms[k]);
  }

  var showH = true, ball = true;

  function buildLayers() {
    var layers = [];
    var bondData = ball ? (showH ? bonds : bondsNoH) : [];
    if (bondData.length) {
      layers.push(new deck.LineLayer({
        id: 'mol-bonds',
        data: bondData,
        coordinateSystem: deck.COORDINATE_SYSTEM.CARTESIAN,
        getSourcePosition: function (d) { return d.s; },
        getTargetPosition: function (d) { return d.t; },
        getColor: [168, 182, 200, 235],
        getWidth: 5,
        widthUnits: 'pixels',
        widthMinPixels: 2,
        pickable: false
      }));
    }
    layers.push(new deck.ScatterplotLayer({
      id: 'mol-atoms',
      data: showH ? atoms : atomsNoH,
      coordinateSystem: deck.COORDINATE_SYSTEM.CARTESIAN,
      getPosition: function (d) { return d.p; },
      getRadius: function (d) { return d.r; },
      radiusUnits: 'pixels',
      getFillColor: function (d) { return d.c; },
      stroked: true,
      getLineColor: [18, 24, 34, 220],
      getLineWidth: 1,
      lineWidthUnits: 'pixels',
      pickable: false
    }));
    return layers;
  }

  var deckgl = new deck.Deck({
    canvas: 'cv',
    width: '100%',
    height: '100%',
    views: new deck.OrbitView({ target: [0, 0, 0], fovy: 20 }),
    initialViewState: { target: [0, 0, 0], rotationX: 30, rotationOrbit: -26, zoom: 0.7 },
    controller: true,
    layers: buildLayers()
  });

  document.getElementById('ball').addEventListener('click', function () {
    ball = !ball;
    this.className = ball ? 'on' : '';
    this.textContent = ball ? '球棍' : '只显示原子';
    deckgl.setProps({ layers: buildLayers() });
  });

  document.getElementById('showh').addEventListener('change', function () {
    showH = this.checked;
    document.getElementById('n').textContent = showH ? atoms.length : atomsNoH.length;
    deckgl.setProps({ layers: buildLayers() });
  });

  window.__deck = deckgl;
})();
</script>
</body>
</html>
Language: this page is in English; the demo keeps Chinese interface labels and code comments. The Chinese page carries the full notes and the same runnable file.

More business examples

deck.gl · APIScatterplotLayer deck.gl · APILineLayer deck.gl · APIOrbitView