The simplest way to display and style a 3Dmol viewer is by embedding 3Dmol parameters within a URL or within HTML tags.
However, if you are interacting with this viewer from your own web pages then you may want to take advantage of the 3Dmol API.
Here we will use the API to create, load and style the 3Dmol instance. This tutorial assumes a basic knowledge of HTML and JavaScript.
Creating the 3DMol instance
First, make sure your HTML document links to the 3Dmol code.
<script src="https://3Dmol.org/build/3Dmol-min.js"></script>Now create a container element in the HTML document that will hold the visualization.
<div id="container-01" class="mol-container"></div>Note: 3Dmol will adopt the size of the container so we need to make sure this size has been explicitly set (i.e. use CSS or an inline style attribute).
<style>
.mol-container {
width: 60%;
height: 400px;
position: relative;
}
</style>Once the script has loaded and the container exists, create a viewer. The core API accepts an HTML element, an element ID, or a jQuery-wrapped element; jQuery is not required.
To make sure everything works, we are going to add a sphere, set the camera, render the scene, then add a zoom.
<script>
let element = document.querySelector('#container-01');
let config = { backgroundColor: 'orange' };
let viewer = $3Dmol.createViewer( element, config );
viewer.addSphere({ center: {x:0, y:0, z:0}, radius: 10.0, color: 'green' });
viewer.zoomTo();
viewer.render();
viewer.zoom(0.8, 2000);
</script>Documentation: $3Dmol.createViewer()
If this has worked, you should see a rather fetching green ball in front of an orange background. If not, then now's a good time to get familiar with the developer console on your favourite browser and check for typos (Firefox, Chrome, ...)
Documentation: $3Dmol.GLViewer API
Loading data dynamically
Use fetch() to load PDB data from a URL, then pass the text to the viewer. Check the response before using it so that a missing file produces a useful error.
async function loadProtein(viewer, pdbUri) {
const response = await fetch(pdbUri);
if (!response.ok) {
throw new Error(`Failed to load PDB: ${response.status}`);
}
const data = await response.text();
viewer.removeAllModels();
viewer.addModel(data, 'pdb');
viewer.setStyle({}, {cartoon: {color: 'spectrum'}});
viewer.zoomTo();
viewer.render();
viewer.zoom(1.2, 1000);
}
const viewer = $3Dmol.createViewer(element, config);
loadProtein(viewer, '/path/to/your/pdb/files/1ycr.pdb')
.catch(error => console.error(error));The loading example is an alternative to the first example: reuse its existing viewer, or create a viewer in a separate container. The /path/to/your/pdb/files/1ycr.pdb URL is a placeholder for your own file. A call to addModel parses data already in memory; it does not fetch a URL.
All these methods (and more) are covered in detail in the API documentation for GLViewer.
The interactive examples below include the 1YCR protein, so they also work when this documentation is opened as a local file.
Note on using external data files (CORS)
When fetching a file from another origin, that server must allow the request through CORS. Browsers also restrict fetching local files through file://. Serve your own page and PDB file over HTTP, or use a data server that permits cross-origin requests.
Dynamic styles
The API lets your page respond to browser events by changing the molecular scene.
Another advantage is that this also gives you more flexibility with styling.
Here we create our own function that will decide on the color of a particular atom based on its own properties:
let colorAsSnake = function(atom) {
return atom.resi % 2 == 0 ? 'white' : 'green';
};Apply that coloring function to an AtomSelectionSpec (here, all atoms in chain 'A'). The second argument is an AtomStyleSpec.
viewer.setStyle({chain: 'A'}, {cartoon: {colorfunc: colorAsSnake}});Updating and disposing a viewer
setStyle replaces the representations on the selected atoms. Use GLViewer#addStyle
to add representations while keeping existing ones. After either operation, call
GLViewer#render to display the change; the interactive example performs
this final render for you. An empty selection object selects all atoms, while
model restricts a selection to a particular model.
Keep the viewer instance when updating a page. GLViewer#clear removes its
scene contents for reuse. When the view is no longer needed, GLViewer#destroy
releases controls, timers, and graphics resources permanently. See that method
for automatic cleanup when a container is removed and the autoDestroy option.
For trajectories, GLViewer#addModelsAsFrames loads multiple frames into
one model. Await GLViewer#setFrame before rendering a chosen frame.
For surfaces, follow the asynchronous return contract of GLViewer#addSurface
before exporting an image or changing a completed surface.