Skip to content

JavaScript Module

The viewer runs in any web page without Python. It is the same engine that the Python package inlines into its HTML files, so the interface, settings and features are identical.

Live Demo Playground

Quick start

<div id="viewer" style="height: 420px"></div>

<script src="https://cdn.jsdelivr.net/gh/kangmg/aseview@main/aseview/viewer_assets/aseview-viewer.js"></script>
<script>
  const viewer = new ASEView.MolecularViewer('#viewer', { style: 'glossy' });
  viewer.setData({
    symbols: ['O', 'H', 'H'],
    positions: [[0, 0, 0.117], [0, 0.757, -0.469], [0, -0.757, -0.469]],
  });
</script>

The same viewer running on this page (with chrome: 'minimal', which hides the sidebar and toolbar). The buttons call setSettings():

The script defines one global, ASEView, and needs no other files: three.js, the styles, the themes and the GIF encoder are bundled in. For stable pages, pin a release instead of @main:

https://cdn.jsdelivr.net/gh/kangmg/aseview@v1.0.0-beta.1/aseview/viewer_assets/aseview-viewer.js

Creating a viewer

const viewer = new ASEView.MolecularViewer(container, settings);
Class Viewer
ASEView.MolecularViewer Structures and trajectories
ASEView.OverlayViewer Several structures in one frame
ASEView.NormalViewer Vibrational modes
ASEView.FragSelector 2D/3D atom picker
ASEView.SurfaceViewer Isosurfaces
  • container is an element or a CSS selector. The viewer fills it, so give it a height.
  • settings is optional: viewer settings in camelCase, e.g. { theme: 'dark', showCell: false, fps: 30 }. Values are validated and an unknown key throws.

All classes return the same viewer object with the same methods. The class only decides how setData() reads a bare list of frames.

Loading data

setData() accepts three forms:

viewer.setData(frame);                  // one structure
viewer.setData([frame1, frame2, ...]);  // a trajectory (OverlayViewer: one entry per structure)
viewer.setData({ mode, frames, ... });  // a full payload, needed for normal modes and surfaces

Frames

A frame is one structure. Only symbols and positions are required:

{
  symbols: ['C', 'H', 'O', ...],
  positions: [[x, y, z], ...],             // Å
  cell: [[ax, ay, az], [bx, by, bz], [cx, cy, cz]],
  pbc: [true, true, true],
  energy: -123.456,                        // eV, for the energy plot
  forces: [[fx, fy, fz], ...],             // eV/Å, arrows and the Fmax plot
  charges: [0.1, -0.2, ...],               // colorBy: 'charge'
  magmoms: [0.0, 1.2, ...],                // colorBy: 'magmom'
  fixed: [1, 4, ...],                      // indices of fixed atoms
  fragments: [0, 0, 1, 1, null, ...],      // fragment per atom, colorBy: 'fragment'
  fragment_labels: ['water', 'ammonia'],
  species: [                               // partial occupancy per site
    [{ symbol: 'Fe', occupancy: 0.6 }, { symbol: 'Mn', occupancy: 0.3 }], ...
  ],
  arrays: { fixed: [true, false, ...], move_mask: [[true, true, false], ...] },
  name: 'Molecule 1',                      // label (overlay rows)
}

fixed is an index list, not a boolean mask; boolean or per-axis selective-dynamics masks go under arrays.fixed and arrays.move_mask. Python's MolecularData.from_atoms() writes exactly this format.

Element visibility and opacity follow each site's frame.symbols identity. For mixed occupancy, species supplies sector colors and fractions; hiding the site symbol hides the entire site, even if its sectors name other elements. Fading the site affects its occupied sectors while the vacancy marker stays opaque. The maps do not edit the occupancy fractions.

Element controls and bond detection

viewer.setSettings({
  elementVisibility: { H: false },
  elementOpacities: { C: 0.35, O: 0.7 },
  opacity: 0.8,
  customBondCutoffs: true,
  bondCutoffs: { 'C-H': 1.2, 'H-H': 0 },
});

The Python equivalents are element_visibility, element_opacities, custom_bond_cutoffs and bond_cutoffs. Empty element maps use visible, opacity-1 defaults. Keys are case-sensitive element symbols (including X); visibility values are booleans and opacities are finite numbers in [0, 1]. The Visibility checkboxes retain slider values when hidden. Its Reset clears both element maps, preserving colors, global and fragment settings. Both maps work independently of colorBy.

customElementAppearance (Python custom_element_appearance) defaults to true. The Per-element opacity switch turns both maps on or off while retaining their values. When off, global, fragment and structure opacity still apply; the element rows are hidden until the switch is enabled again.

Atom alpha multiplies global, element, assigned fragment and applicable overlay structure opacities. Hidden or zero-alpha atoms cannot be picked and have no incident bonds; bond alpha is the smaller endpoint alpha. Fully opaque atoms and bonds retain instancing. Fractional ones need more draw calls for camera depth sorting in standard and high-performance modes. Normal styles blend alpha; Neon stays additive. Intersecting translucent surfaces can show the usual depth-sorting artifacts; this is not order-independent transparency or glass refraction. See element opacity.

bondCutoffs values are maximum bond detection distances in Å, enabled by customBondCutoffs: true. Detection is strict (distance < cutoff); 0 disables a pair and unlisted pairs retain radius-based defaults. Reversed 'H-C' becomes canonical 'C-H'. The Per-pair cutoffs UI uses the same map and retains it when custom mode is disabled. Changing these values changes detected bonds, including periodic neighbours, while coordinates and actual interatomic distances stay unchanged.

Payloads per viewer

const viewer = new ASEView.NormalViewer('#viewer', { showModeVector: true });
viewer.setData({
  mode: 'normal',
  frames: [water],                               // equilibrium structure
  normalModes: {
    vectors: [                                   // [mode][atom][xyz] displacements
      [[0, 0, -0.07], [0, 0.42, 0.56], [0, -0.42, 0.56]],
      [[0, 0.07, 0], [0, -0.56, 0.42], [0, 0.56, 0.42]],
    ],
    frequencies: ['1595.32', '3657.05'],         // labels in cm⁻¹
    isImaginary: [false, false],
    nFrames: 30,                                 // optional: frames per period
  },
});
const viewer = new ASEView.FragSelector('#viewer', { copyFormat: 'extxyz' });
viewer.setData({ mode: 'fragment', frames: [molecule], selected: [0, 1, 2] });
viewer.setSelection([1, 2, 4]);
viewer.getSelection();   // [1, 2, 4]

Isosurfaces are triangle meshes. Python extracts them from CUBE/CHGCAR grids; in JavaScript you pass the shells directly:

const viewer = new ASEView.SurfaceViewer('#viewer', { surfaceStyle: 'solid' });
viewer.setData({
  mode: 'surface',
  frames: [molecule],
  surfaceFrames: [[                              // per frame: a list of named surfaces
    {
      label: 'HOMO',
      payload: {
        surface_kind: 'orbital',
        surfaces: [                              // one entry per shell
          { phase: 'positive', color: '#ef4444', opacity: 0.65,
            vertices: [[x, y, z], ...], faces: [[0, 1, 2], ...] },
          { phase: 'negative', color: '#2563eb', opacity: 0.65,
            vertices: [...], faces: [...] },
        ],
      },
    },
  ]],
});

To show a CUBE file without writing meshes, build the page in Python with SurfaceViewer and save_html().

Methods

Method Description
setData(data) Load a frame, a frame list or a payload (above)
setSettings(patch) Change settings; validated, unknown keys throw
getSettings() Current settings
setFrame(index) Show one frame
play(on = true) Start or stop playback (speed: the fps setting, in frames per second)
resetView() Back to the starting camera
applyViewPreset(name) Look along x, y, z, a, b, c, or auto
measure(on = true) Open/close Measure for typed indices or atom clicks; recorded measurements remain visible
select(keys) Show an ordered measurement draft with up to four pick keys (structure\|site\|a,b,c), including when Measure is closed
getSelection() / setSelection(indices) Fragment selector selection
toPNG(scale = 2, transparent = false) PNG of the current view as a data URL
downloadPNG({ scale, transparent, filename }) Save a PNG
toGIF({ scale, fps, step, maxFrames }) Animated GIF of every frame, as a Promise<Blob>
downloadGIF({ scale, fps, step, maxFrames, filename }) Save a GIF
copyStructure(which = 'frame', format = 'xyz') Copy 'frame' or 'all' as xyz, extxyz, cif or vasp-poscar; resolves to the text
destroy() Stop playback, release the WebGL context and empty the container

Browsers keep only about 16 WebGL contexts per page, so call destroy() on viewers you remove.

ASEView.version is the release version and ASEView.exportSchema() returns the settings schema, the data behind Viewer Settings.

Driving a saved page from its parent

A page written by Python (or the VS Code extension) can be embedded in an iframe and controlled with postMessage:

const frame = document.querySelector('iframe').contentWindow;
frame.postMessage({ type: 'setSettings', settings: { theme: 'dark' } }, '*');
Message Effect
{ type: 'setData', data, settings? } Load data (setMolecularData is an alias)
{ type: 'setSettings', settings } Change settings
{ type: 'setFrame', index } Jump to a frame

When ready, the page posts { type: 'viewerLoaded', version: 3, viewer } to its parent. Messages from any window other than the parent are ignored.