3dmol.js Molecular Visualization Library

repository·master·Indexed 21 days ago

https://github.com/3dmol/3dmol.js

An object-oriented, WebGL-accelerated JavaScript/TypeScript library for high-performance online molecular visualization. It supports a wide range of formats (including PDB, SDF, MOL2, XYZ, and CIF) and provides a programmatic API via GLViewer, GLModel, and AtomSpec. The library can be embedded via HTML attributes, script tags, or npm/yarn. Additionally, the py3Dmol Python wrapper allows for interactive 3D molecular rendering and animation within IPython and Jupyter notebook environments.

Tokens
27.2K
Snippets
102
Records
122
Agent score
77%

What's inside 3dmol.js

  1. Understand the core 3Dmol.js abstractions: GLViewer, GLModel, and AtomSpec

    master

    3Dmol.js is built around three primary concepts:

    1. $3Dmol.GLViewer: Every viewer canvas corresponds to a GLViewer object. This object is used to set viewer properties and to create/manipulate molecular models, surfaces, and geometric shapes.
    2. $3Dmol.GLModel: Represents specific molecular data. Each model object stores its own rendering data and acts as a reference to a defined part of the scene.
    3. AtomSpec: JavaScript objects used to manipulate and style models (e.g., defining colors or styles for specific atoms).
  2. Apply dynamic styles using color functions

    master

    The setStyle method allows for highly flexible styling by providing a function instead of a static color. This function is called for each atom and can determine color based on atom properties like residue number (resi).

    To use this, define a function that accepts an atom object and returns a color string, then pass it to the colorfunc key within a style object.

    // Define a function that colors atoms based on residue number
    let colorAsSnake = function(atom) {
      return atom.resi % 2 == 0 ? 'white' : 'green';
    };
    
    // Apply the function to a specific selection (e.g., all atoms in chain 'A')
    viewer.setStyle({chain: 'A'}, {cartoon: {colorfunc: colorAsSnake}});
  3. View structures via 3Dmol.js URL query strings

    master

    You can instantly view molecular structures by appending a query string to the 3Dmol.js viewer URL: https://3Dmol.org/viewer.html?[query string].

    The query string allows you to specify a structure, select specific atoms, and apply visual styles without writing code. Specifiers are separated by the & character and are processed in the order they appear.

    https://3Dmol.org/viewer.html?pdb=1YCR&select=chain:A&style=cartoon;stick:radius~0.1&surface=opacity:0.8;colorscheme:whiteCarbon&select=chain:B&style=cartoon;line&select=resi:19,23,26;chain:B&style=cartoon;stick&labelres=backgroundOpacity:0.8;fontSize:14
  4. Explore 3Dmol.js tutorials

    master

    The 3Dmol.js tutorial suite provides several paths for integration depending on your use case:

    • Use 3Dmol within your code: For programmatic control and integration into custom applications.
    • Embedding a 3Dmol Viewer: For simple HTML/JavaScript embedding into web pages.
    • Active Learning with 3Dmol.js: For using the library within interactive learning environments.
    • Hosted 3Dmol.js viewer: For using a pre-hosted version of the viewer via URL parameters.
  5. Create a 3Dmol instance using $3Dmol.createViewer()

    master

    To use the 3Dmol API, first include the 3Dmol library in your HTML. Then, create a container element (e.g., a <div>) with an explicit size set via CSS, as the viewer will adopt the container's dimensions. Use $3Dmol.createViewer(element, config) to initialize the viewer.

    Common workflow after creation:

    1. Add geometry (e.g., addSphere).
    2. Set the camera position using zoomTo().
    3. Call render() to draw the scene.
    4. Optionally use zoom(scale, duration) for animated transitions.
    <!-- 1. Include the library -->
    <script src="https://3Dmol.org/build/3Dmol-min.js"></script>
    
    <!-- 2. Create a sized container -->
    <div id="container-01" style="width: 60%; height: 400px; position: relative;"></div>
    
    <script>
      // 3. Initialize the viewer
      let element = document.querySelector('#container-01');
      let config = { backgroundColor: 'orange' };
      let viewer = $3Dmol.createViewer( element, config );
    
      // 4. Add content and render
      viewer.addSphere({ center: {x:0, y:0, z:0}, radius: 10.0, color: 'green' });
      viewer.zoomTo();
      viewer.render();
      viewer.zoom(0.8, 2000);
    </script>
  6. Self-host the 3Dmol.js active learning environment

    master

    To host your own instance of the 3Dmol.js active learning environment (which allows instructors to create sessions that students can join to see synchronized molecular views), you can use a lightweight Flask webserver.

    Setup on Ubuntu Linux

    1. Install system dependencies: apt install npm python3-pip git.
    2. Install Python dependencies: pip3 install flask flask_socketio eventlet.
    3. Clone the repository: git clone https://github.com/3dmol/3Dmol.js.git.
    4. Build the project: cd 3Dmol.js && npm install.
    5. Run the server: cd learning-environment && python3 server.py.

    Accessing the Viewer

    • The server defaults to port 5000. You can specify a different port using the -p <PORT> flag.
    • The viewer is accessible at http://HOSTNAME:5000/static/viewer.html.
    • You can pass molecules as relative paths via the url= query parameter. For example: http://localhost:5000/static/viewer.html?url=molecule.sdf&style=stick.

    Security Note

    Do not run the server as a superuser to use privileged port 80 without consulting a network security specialist. Ensure your network allows external connections to the chosen port.

    #install dependencies
    apt install npm python3-pip git
    pip3 install flask flask_socketio eventlet
    #get latest version from git
    git clone https://github.com/3dmol/3Dmol.js.git
    #build with npm
    cd 3Dmol.js
    npm install
    #run a standalone flask server
    cd learning-environment
    #can optionally specify a port with -p <PORT>, default is 5000
    python3 server.py
  7. Specify a structure in a 3Dmol.js URL

    master

    The structure identifier is the first part of the query string. You can fetch molecules using one of three methods:

    • pdb=[PDB ID]: Fetches from the Protein Data Bank.
    • cid=[PubChem CID]: Fetches from the PubChem database.
    • url=[URL]: Fetches from an arbitrary URL.

    If using url=, the file format is typically inferred from the file extension (e.g., .sdf). You can manually specify the format using the type parameter.

    https://3Dmol.org/viewer.html?pdb=4KW4
    
    https://3Dmol.org/viewer.html?url=https://3dmol.org/tests/test_structs/benzene.sdf&type=sdf
  8. Select atoms using atom selectors

    master

    Use the select= parameter to target specific atoms. Selectors are formatted as a semi-colon separated list of property:value pairs. All specified properties must match for an atom to be selected.

    • Multiple properties: Use ; to combine properties (e.g., resn:TRP;chain:B selects all Tryptophans on chain B).
    • Multiple values: Use , for a single property to select any matching value (e.g., resi:19,23,26;chain:B selects residues 19, 23, and 26 on chain B).

    Selectors can be chained with styles to create complex scenes.

    https://3Dmol.org/viewer.html?pdb=1YCR&select=resn:TRP;chain:B&style=stick
    
    https://3Dmol.org/viewer.html?pdb=1YCR&select=resi:19,23,26;chain:B&style=stick
  9. Load molecular data dynamically

    master

    You can load molecular data (like PDB files) from external sources using standard JavaScript fetch or jQuery AJAX. Once the raw data is retrieved, pass it to the viewer using v.addModel(data, "format"), where "format" is the file type (e.g., "pdb").

    Note on CORS: When loading data from a different domain, the server hosting the data must allow Cross-origin resource sharing (CORS).

    let viewer = $3Dmol.createViewer( element, config );
    let pdbUri = '/path/to/your/pdb/files/1ycr.pdb';
    
    jQuery.ajax( pdbUri, {
      success: function(data) {
        let v = viewer;
        v.addModel( data, "pdb" );                       /* load data */
        v.setStyle({}, {cartoon: {color: 'spectrum'}});  /* style all atoms */
        v.zoomTo();                                      /* set camera */
        v.render();                                      /* render scene */
        v.zoom(1.2, 1000);                               /* slight zoom */
      },
      error: function(hdr, status, err) {
        console.error( "Failed to load PDB " + pdbUri + ": " + err );
      },
    });
  10. Initialize and use 3Dmol.js via JavaScript API

    master

    For programmatic control, you can initialize a viewer by targeting a DOM element's ID using $3Dmol.createViewer(). You can then download molecular data (using PDB queries or files) and apply styles using viewer.setStyle() and viewer.render().

    // 1. Create the viewer
    var viewer = $3Dmol.createViewer($("#div"));
    
    // 2. Download and display a model (e.g., PDB: 1MO8)
    $3Dmol.download("pdb:1MO8", viewer, {multimodel: true, frames: true}, function() {
        // 3. Set style and render
        viewer.setStyle({}, {cartoon: {color: "spectrum"}});
        viewer.render();
    });