Access instantiated viewers via $3Dmol.viewers
masterGLViewer instance programmatically using the id of the container div. The instances are stored in the $3Dmol.viewers object.repository·master·Indexed 21 days ago
https://github.com/3dmol/3dmol.jsAn 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.
GLViewer instance programmatically using the id of the container div. The instances are stored in the $3Dmol.viewers object.3Dmol.js is built around three primary concepts:
$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.$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.AtomSpec: JavaScript objects used to manipulate and style models (e.g., defining colors or styles for specific atoms).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}});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:14The 3Dmol.js tutorial suite provides several paths for integration depending on your use case:
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:
addSphere).zoomTo().render() to draw the scene.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>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.
apt install npm python3-pip git.pip3 install flask flask_socketio eventlet.git clone https://github.com/3dmol/3Dmol.js.git.cd 3Dmol.js && npm install.cd learning-environment && python3 server.py.5000. You can specify a different port using the -p <PORT> flag.http://HOSTNAME:5000/static/viewer.html.url= query parameter. For example: http://localhost:5000/static/viewer.html?url=molecule.sdf&style=stick.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.pyThe 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=sdfUse 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.
; to combine properties (e.g., resn:TRP;chain:B selects all Tryptophans on chain B)., 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=stickYou 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 );
},
});To use the py3Dmol widget in an IPython or Jupyter environment, install the package from PyPI using pip.
pip install py3DmolFor 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();
});