GLViewer
Source: GLViewer.ts
WebGL-based molecular viewer. Create one with createViewer inside a
container with a nonzero width and height. Load molecular data with
GLViewer#addModel, select atoms with AtomSelectionSpec, and
style them with AtomStyleSpec. Call GLViewer#render after
changing models or styles. Call GLViewer#destroy when finished.
Constructor
new GLViewer(): GLViewerInstance Methods
addArrow(spec: ArrowSpec): GLShape
Create and add arrow shape
Parameters
spec(ArrowSpec) — Style specification
Returns
Example
$3Dmol.download("pdb:4DM7",viewer,{},function(){
viewer.setBackgroundColor(0xffffffff);
viewer.addArrow({
start: {x:-10.0, y:0.0, z:0.0},
end: {x:0.0, y:-10.0, z:0.0},
radius: 1.0,
radiusRadio:1.0,
mid:1.0,
clickable:true,
callback:function(){
this.color.setHex(0xFF0000FF);
viewer.render( );
}
});
viewer.render();
});addAsOneMolecule(data: string, format: string): GLModel
Create and add model to viewer. Given multimodel file and its format,
all structures are combined into one model, displayed together rather than
as animation frames. Use GLViewer#addModels for separate models.
Parameters
data(string) — Input dataformat(string) — Input format (see FileFormats)
Returns
Example
$3Dmol.get('../test_structs/multiple.sdf', function(data){
viewer.addAsOneMolecule(data, "sdf");
viewer.zoomTo();
viewer.render();
});Combine the same input into one model displaying all atoms.
var pdb = [
"MODEL 1",
"HETATM 1 C1 LIG A 1 -0.600 -1.500 0.000 1.00 0.00 C",
"HETATM 2 O1 LIG A 1 0.600 -1.500 0.000 1.00 0.00 O",
"ENDMDL",
"MODEL 2",
"HETATM 1 C1 LIG A 1 -0.600 1.500 0.000 1.00 0.00 C",
"HETATM 2 O1 LIG A 1 0.600 1.500 0.000 1.00 0.00 O",
"ENDMDL"
].join("\n");
var model = viewer.addAsOneMolecule(pdb, "pdb");
model.setStyle({}, {stick: {radius: 0.25}, sphere: {scale: 0.3}});
viewer.addLabel("One model / four atoms together", {
useScreen: true, position: {x: 12, y: 20, z: 0},
fontSize: 14, fontColor: "black", showBackground: false
});
viewer.zoomTo();
viewer.render();addBox(spec: BoxSpec): GLShape
Create and add box shape. This method provides a shorthand
way to create a box shape object
Parameters
spec(BoxSpec) — Box shape style specification
Returns
Example
viewer.addLine({color:'red',start:{x:0,y:0,z:0},end:{x:5,y:0,z:0}});
viewer.addLine({color:'blue',start:{x:0,y:0,z:0},end:{x:0,y:5,z:0}});
viewer.addLine({color:'green',start:{x:0,y:0,z:0},end:{x:0,y:0,z:5}});
viewer.addBox({center:{x:0,y:0,z:0},dimensions: {w:3,h:4,d:2},color:'magenta'});
viewer.zoomTo();
viewer.rotate(45, {x:1,y:1,z:1});
viewer.render();addCurve(spec: CurveSpec): GLShape
Create and add Curve shape
Parameters
spec(CurveSpec) — Style specification
Returns
Example
viewer.addCurve({points: [{x:0.0,y:0.0,z:0.0}, {x:5.0,y:3.0,z:0.0}, {x:5.0,y:7.0,z:0.0}, {x:0.0,y:10.0,z:0.0}],
radius:0.5,
smooth: 10,
fromArrow:false,
toArrow: true,
color:'orange',
});
viewer.addCurve({points: [{x:-1,y:0.0,z:0.0}, {x:-5.0,y:5.0,z:0.0}, {x:-2,y:10.0,z:0.0}],
radius:1,
fromArrow:true,
toArrow: false,
color:'purple',
});
viewer.zoomTo();
viewer.render();addCustom(spec: CustomShapeSpec): GLShape
Add custom shape component from user supplied function
Parameters
spec(CustomShapeSpec) — Style specification
Returns
Example
function triangle(viewer) {
var vertices = [];
var normals = [];
var colors = [];
var r = 20;
//triangle
vertices.push(new $3Dmol.Vector3(0,0,0));
vertices.push(new $3Dmol.Vector3(r,0,0));
vertices.push(new $3Dmol.Vector3(0,r,0));
normals.push(new $3Dmol.Vector3(0,0,1));
normals.push(new $3Dmol.Vector3(0,0,1));
normals.push(new $3Dmol.Vector3(0,0,1));
colors.push({r:1,g:0,b:0});
colors.push({r:0,g:1,b:0});
colors.push({r:0,g:0,b:1});
var faces = [ 0,1,2 ];
var spec = {vertexArr:vertices, normalArr: normals, faceArr:faces,color:colors};
viewer.addCustom(spec);
}
triangle(viewer);
viewer.render();addCylinder(spec: CylinderSpec): GLShape
Create and add cylinder shape
Parameters
spec(CylinderSpec) — Style specification
Returns
Example
viewer.setBackgroundColor(0xffffffff);
viewer.addCylinder({start:{x:0.0,y:0.0,z:0.0},
end:{x:10.0,y:0.0,z:0.0},
radius:1.0,
fromCap:1,
toCap:2,
color:'red',
hoverable:true,
clickable:true,
callback:function(){ this.color.setHex(0x00FFFF00);viewer.render( );},
hover_callback: function(){ viewer.render( );},
unhover_callback: function(){ this.color.setHex(0xFF000000);viewer.render( );}
});
viewer.addCylinder({start:{x:0.0,y:2.0,z:0.0},
end:{x:0.0,y:10.0,z:0.0},
radius:0.5,
fromCap:false,
toCap:true,
color:'teal'});
viewer.addCylinder({start:{x:15.0,y:0.0,z:0.0},
end:{x:20.0,y:0.0,z:0.0},
radius:1.0,
color:'black',
fromCap:false,
toCap:false});
viewer.render();addIsosurface(data: VolumeData, spec: IsoSurfaceSpec): GLShape
Construct isosurface from volumetric data. This is more flexible
than addVolumetricData, but can not be used with py3Dmol.
Parameters
data(VolumeData) — volumetric dataspec(IsoSurfaceSpec) — Shape style specification
Returns
Example
$3Dmol.get('../test_structs/benzene-homo.cube', function(data){
var voldata = new $3Dmol.VolumeData(data, "cube");
viewer.addIsosurface(voldata, {isoval: 0.01,
color: "blue"});
viewer.addIsosurface(voldata, {isoval: -0.01,
color: "red"});
viewer.zoomTo();
viewer.render();
});addLabel(
text: string,
options: LabelSpec,
sel: AtomSelectionSpec,
noshow: boolean,
): Label
Add label to viewer
Parameters
text(string) — Label textoptions(LabelSpec) — Label style specificationsel(AtomSelectionSpec) — Position at the selection's mean atom position, overriding options.position.noshow(boolean) — if true, do not immediately display label - when adding multiple labels this is more efficient
Returns
Example
$3Dmol.download("pdb:2EJ0",viewer,{},function(){
viewer.addLabel("Aromatic", {position: {x:-6.89, y:0.75, z:0.35}, backgroundColor: 0x800080, backgroundOpacity: 0.8});
viewer.addLabel("Label",{font:'sans-serif',fontSize:18,fontColor:'white',fontOpacity:1,borderThickness:1.0,
borderColor:'red',borderOpacity:0.5,backgroundColor:'black',backgroundOpacity:0.5,
position:{x:50.0,y:0.0,z:0.0},inFront:true,showBackground:true});
viewer.setStyle({chain:'A'},{cross:{hidden:true}});
viewer.setStyle({chain:'B'},{cross:{hidden:false,
linewidth:1.0,
colorscheme:'greenCarbon'}});
viewer.setStyle({chain:'C'},{cross:{hidden:false,
linewidth:1.0,
radius:0.5}});
viewer.setStyle({chain:'D'},{cross:{hidden:false,
linewidth:10.0}});
viewer.setStyle({chain:'E'},{cross:{hidden:false,
linewidth:1.0,
color:'black'}});
viewer.render();
});addLine(spec: LineSpec): GLShape
Create and add line shape
Parameters
spec(LineSpec) — Style specification, can specify dashed, dashLength, and gapLength
Returns
Example
$3Dmol.download("pdb:2ABJ",viewer,{},function(){
viewer.setViewStyle({style:"outline"});
viewer.setStyle({chain:'A'},{sphere:{hidden:true}});
viewer.setStyle({chain:'D'},{sphere:{radius:3.0}});
viewer.setStyle({chain:'G'},{sphere:{colorscheme:'greenCarbon'}});
viewer.setStyle({chain:'J'},{sphere:{color:'blue'}});
viewer.addLine({dashed:true,start:{x:0,y:0,z:0},end:{x:100,y:100,z:100}});
viewer.render();
});addLineDashed(spec: CylinderSpec, s: GLShape)
Add dashed line to shape
Parameters
spec(CylinderSpec)s(GLShape)
addMesh(mesh: Mesh): number
Adds an explicit mesh as a surface object.
Parameters
mesh(Mesh)
Returns
number— surfid
addModel(
data?: string | ArrayBuffer | Uint8Array | Object,
format?: string,
options?: ParserOptionsSpec,
): GLModel
Parse molecular data and add a model to the viewer. This does not fetch a
URL; use download, get, or getbin to retrieve data.
Set styles and call render() to display the model. Without data, creates
an empty model that can be populated with GLModel#addAtoms.
Parameters
data(string | ArrayBuffer | Uint8Array | Object, optional) — File contents or parser-specific input.format(string, optional) — Format key or filename (see FileFormats).
Specify the format explicitly when known; content-based guessing is limited.options(ParserOptionsSpec, optional) — Options supported by the selected parser.
Returns
Example
viewer.setViewStyle({style:"outline"});
$3Dmol.get('data/1fas.pqr', function(data){
viewer.addModel(data, "pqr");
$3Dmol.get("data/1fas.cube",function(volumedata){
viewer.addSurface($3Dmol.SurfaceType.VDW, {opacity:0.85,voldata: new $3Dmol.VolumeData(volumedata, "cube"), volscheme: new $3Dmol.Gradient.RWB(-10,10)},{});
viewer.render();
});
viewer.zoomTo();
});addModels(
data: string | ArrayBuffer | Uint8Array | Object,
format: string,
options?: ParserOptionsSpec,
): Array.<GLModel>
Parse a multimodel file into separate models in this viewer.
For a single model with animation frames, use GLViewer#addModelsAsFrames.
For one combined model, use GLViewer#addAsOneMolecule.
Parameters
data(string | ArrayBuffer | Uint8Array | Object) — File contents or parser-specific input.format(string) — Input format (see FileFormats).options(ParserOptionsSpec, optional) — Parser options; multimodel and frames are enabled internally.
Returns
Array.<GLModel>— The viewer's complete model array, including pre-existing
models and any empty slots left by model removal; not only the newly added models.
Example
Load both structures as independently styled models.
var pdb = [
"MODEL 1",
"HETATM 1 C1 LIG A 1 -0.600 -1.500 0.000 1.00 0.00 C",
"HETATM 2 O1 LIG A 1 0.600 -1.500 0.000 1.00 0.00 O",
"ENDMDL",
"MODEL 2",
"HETATM 1 C1 LIG A 1 -0.600 1.500 0.000 1.00 0.00 C",
"HETATM 2 O1 LIG A 1 0.600 1.500 0.000 1.00 0.00 O",
"ENDMDL"
].join("\n");
var models = viewer.addModels(pdb, "pdb");
models[0].setStyle({}, {stick: {color: "royalblue", radius: 0.3}});
models[1].setStyle({}, {stick: {color: "orange", radius: 0.3}});
viewer.addLabel("Two models / two atoms each", {
useScreen: true, position: {x: 12, y: 20, z: 0},
fontSize: 14, fontColor: "black", showBackground: false
});
viewer.zoomTo();
viewer.render();addModelsAsFrames(data: string, format: string): GLModel
Create and add model to viewer. Given multimodel file and its format,
each structure becomes a frame of the same model, initially displaying
frame zero. Use GLViewer#setFrame for a single frame or
GLViewer#animate for playback.
Parameters
data(string) — Input dataformat(string) — Input format (see FileFormats)
Returns
Example
$3Dmol.get('../test_structs/multiple2.xyz', function(data){
viewer.addModelsAsFrames(data, "xyz");
viewer.animate({loop: "forward",reps: 1});
viewer.setStyle({stick:{colorscheme:'magentaCarbon'}});
viewer.zoomTo();
viewer.render();
});Load the same input as one model with two frames.
var pdb = [
"MODEL 1",
"HETATM 1 C1 LIG A 1 -0.600 -1.500 0.000 1.00 0.00 C",
"HETATM 2 O1 LIG A 1 0.600 -1.500 0.000 1.00 0.00 O",
"ENDMDL",
"MODEL 2",
"HETATM 1 C1 LIG A 1 -0.600 1.500 0.000 1.00 0.00 C",
"HETATM 2 O1 LIG A 1 0.600 1.500 0.000 1.00 0.00 O",
"ENDMDL"
].join("\n");
var model = viewer.addModelsAsFrames(pdb, "pdb");
model.setStyle({}, {stick: {radius: 0.25}, sphere: {scale: 0.3}});
// Frame zero is displayed initially; the other structure is not drawn yet.
viewer.addLabel("One model / two frames / frame 0", {
useScreen: true, position: {x: 12, y: 20, z: 0},
fontSize: 14, fontColor: "black", showBackground: false
});
viewer.zoomTo();
viewer.render();addPropertyLabels(
prop: string,
sel: AtomSelectionSpec,
style: LabelSpec,
)
Add property labels. This will generate one label per a selected
atom at the atom's coordinates with the property value as the label text.
Parameters
prop(string) — property namesel(AtomSelectionSpec)style(LabelSpec)
addResLabels(
sel: AtomSelectionSpec,
style: LabelSpec,
byframe: boolean,
): Array.<Label>
Add residue labels. This will generate one label per a
residue within the selected atoms. The label will be at the
centroid of the atoms and styled according to the passed style.
The label text will be [resn][resi]
Parameters
sel(AtomSelectionSpec)style(LabelSpec)byframe(boolean) — if true, create labels for every individual frame, not just current
Returns
Array.<Label>— The newly created labels.
Example
$3Dmol.download("mmtf:2ll5",viewer,{},function(){
viewer.setStyle({stick:{radius:0.15},cartoon:{}});
viewer.addResLabels({hetflag:false}, {font: 'Arial', fontColor:'black',showBackground:false, screenOffset: {x:0,y:0}});
viewer.zoomTo();
viewer.render();
});addShape(shapeSpec: ShapeSpec): GLShape
Add shape object to viewer
Parameters
shapeSpec(ShapeSpec) — style specification for the shape
Returns
- See:
addSphere(spec: SphereSpec): GLShape
Create and add sphere shape. This method provides a shorthand
way to create a spherical shape object
Parameters
spec(SphereSpec) — Sphere shape style specification
Returns
Example
viewer.addSphere({center:{x:0,y:0,z:0},radius:10.0,color:'red'});
viewer.render();addStyle(sel: AtomSelectionSpec, style: AtomStyleSpec)
Merge style properties into selected atoms' existing styles.
Existing representations are retained; properties supplied for the same
representation overwrite matching properties. With one argument, that
argument is a style applied to all atoms. Call render() to display the change.
Parameters
sel(AtomSelectionSpec) — Atom selection specification. Can be omitted to select allstyle(AtomStyleSpec) — style spec to add to specified atoms
Example
$3Dmol.download('pdb:5IRE',viewer,{doAssembly: false},function(m) {
viewer.setStyle({cartoon:{}});
//keep cartoon style, but show thick sticks for chain A
viewer.addStyle({chain:'A'},{stick:{radius:.5,colorscheme:"magentaCarbon"}});
viewer.zoomTo();
viewer.render();
});Replacement on the left; additive styling on the right.
function addPair(x) {
var model = viewer.addModel();
model.addAtoms([
{elem: "C", x: x, y: -0.8, z: 0, bonds: [1], bondOrder: [1]},
{elem: "O", x: x, y: 0.8, z: 0, bonds: [0], bondOrder: [1]}
]);
return model;
}
var left = addPair(-2);
var right = addPair(2);
viewer.setStyle({}, {sphere: {radius: 0.55}});
// setStyle removes the left model's spheres; addStyle retains the right ones.
viewer.setStyle({model: left}, {stick: {radius: 0.2, color: "orange"}});
viewer.addStyle({model: right}, {stick: {radius: 0.2, color: "orange"}});
viewer.addLabel("setStyle", {
position: {x: -2, y: 1.8, z: 0}, alignment: "center",
fontColor: "black", showBackground: false
});
viewer.addLabel("addStyle", {
position: {x: 2, y: 1.8, z: 0}, alignment: "center",
fontColor: "black", showBackground: false
});
viewer.zoomTo();
viewer.render();addSurface(
stype: SurfaceType | string,
style?: SurfaceStyleSpec,
atomsel?: AtomSelectionSpec,
allsel?: AtomSelectionSpec,
focus?: AtomSelectionSpec,
surfacecallback?: function,
): Promise | number
Add surface representation to atoms
Parameters
stype(SurfaceType | string) — Surface type (VDW, MS, SAS, or SES); string names are case-insensitive.style(SurfaceStyleSpec, optional, default: "{}") — Surface material and coloring.atomsel(AtomSelectionSpec, optional, default: "{}") — Atoms whose surface is displayed; defaults to all atoms.allsel(AtomSelectionSpec, optional) — Atoms used to calculate the surface;
defaults to atomsel. A larger selection includes neighboring atoms' occlusion.focus(AtomSelectionSpec, optional) — Prioritize chunks near these atoms; does not change the final surface.surfacecallback(function, optional) — Completion callback. Receives the surface ID normally.
With symmetry preprocessing, receives an array repeating that ID once per contributing model
(an empty array if no models contribute).
Returns
Promise | number— Without a callback, returns a Promise resolving to the numeric surface ID;
its surfid property exposes that ID immediately. With a callback, returns the numeric ID immediately.
Removing the surface stops pending generation and still resolves its original ID (and invokes
the callback); the ID does not imply that the surface still exists. Destroying the viewer
also settles the Promise but suppresses the completion callback.
Use the Promise form to handle computation failures, which reject the Promise.
Example
Use neighboring atoms for occlusion while displaying only the selected surface.
function addPair(x) {
var model = viewer.addModel();
model.addAtoms([
{elem: "C", x: x, y: 0, z: 0},
{elem: "C", x: x + 1.8, y: 0, z: 0}
]);
return model;
}
var left = addPair(-4);
var right = addPair(3);
viewer.setStyle({}, {sphere: {radius: 0.3, color: "black"}});
viewer.addLabel("Isolated atom", {
position: {x: -4, y: 2.3, z: 0}, alignment: "center",
fontColor: "black", showBackground: false
});
viewer.addLabel("Neighbor occlusion", {
position: {x: 3, y: 2.3, z: 0}, alignment: "center",
fontColor: "black", showBackground: false
});
(async function () {
await Promise.all([
viewer.addSurface("VDW", {opacity: 0.8, color: "royalblue"},
{model: left, index: 0}, {model: left, index: 0}),
viewer.addSurface("VDW", {opacity: 0.8, color: "orange"},
{model: right, index: 0}, {model: right})
]);
// Both surfaces are complete before drawing and exporting the image.
viewer.zoomTo();
viewer.zoom(0.65); // Include the surfaces beyond the atom centers.
viewer.render();
var imageURI = viewer.pngURI(); // Use this data URI as an img element's src.
})();addUnitCell(model: GLModel | number, spec: UnitCellStyleSpec)
Create and add unit cell visualization.
Parameters
model(GLModel | number) — Model with unit cell information (e.g., pdb derived). If omitted uses most recently added model.spec(UnitCellStyleSpec) — visualization style
Example
$3Dmol.get('data/1jpy.cif', function(data) {
let m = viewer.addModel(data);
viewer.addUnitCell(m, {box:{color:'purple'},alabel:'X',blabel:'Y',clabel:'Z',alabelstyle: {fontColor: 'black',backgroundColor:'white',inFront:true,fontSize:40},astyle:{color:'darkred', radius:5,midpos: -10}});
viewer.zoomTo();
viewer.render();
});addVolumetricData(
data: string | ArrayBuffer | Uint8Array | Int8Array,
format: String,
spec: VolumetricRendererSpec | IsoSurfaceSpec,
): GLShape | GLVolumetricRender
Construct an isosurface from volumetric data in the specified format.
If spec includes transferfn, create a volumetric renderer instead.
Parameters
data(string | ArrayBuffer | Uint8Array | Int8Array) — Input file contentsformat(String) — Input file formatspec(VolumetricRendererSpec | IsoSurfaceSpec) — Shape style specification
Returns
Example
$3Dmol.get('data/bohr.cube', function(data) {
viewer.addVolumetricData(data, "cube", {isoval: -0.01, color: "red", opacity: 0.95});
viewer.setStyle({cartoon:{},stick:{}});
viewer.zoomTo();
viewer.render();
});addVolumetricRender(
data: VolumeData,
spec: VolumetricRendererSpec,
): GLVolumetricRender
Create volumetric renderer for volumetricData
Parameters
data(VolumeData) — volumetric dataspec(VolumetricRendererSpec) — specification of volumetric render
Returns
animate(options?: Object)
Animate all models in viewer from their respective frames.
Frame-load failures are logged and stop only the affected animation.
Parameters
options(Object, optional, default: "{}") — Playback settings.options.interval(number, optional, default: 100) — Target interval between frames in milliseconds.options.loop(string, optional, default: "\"forward\"") — "forward", "backward", or "backAndForth".options.step(number, optional, default: 1) — Number of frames advanced per update.options.startFrame(number, optional, default: 0) — Starting position in the playback sequence.options.reps(number, optional, default: 0) — Number of repetitions; 0 repeats indefinitely.options.fast(boolean, optional, default: false) — Replay coordinates into existing geometry;
see GLViewer#setFrame for limitations.
By default, models with one frame are also refreshed so direct atom edits and dynamic
color functions take effect during playback.
apngURI(nframes?: number): Promise.<(string|undefined)>
Capture subsequent viewer redraws as an animated PNG data URI.
This method does not start an animation or request redraws; use animate(),
spin(), or render() to produce them. It temporarily replaces the view-change
callback and restores that callback when capture completes.
Resolves to undefined if destroy() occurs before all frames are captured.
Parameters
nframes(number, optional, default: 1) — Number of subsequent redraws to capture.
Returns
Promise.<(string|undefined)>— Base64-encoded PNG data URI, or undefined on cancellation.
atomIsSelected(atom: AtomSpec, sel: AtomSelectionSpec): boolean
Parameters
atom(AtomSpec)sel(AtomSelectionSpec)
Returns
boolean
carveUpExtent(
extent: Array,
atomlist: Array.<AtomSpec>,
atomstoshow: Array.<AtomSpec>,
): Array
Parameters
Returns
Array
center(
sel?: AtomSelectionSpec,
animationDuration?: number,
fixedPath?: Boolean,
)
Re-center the viewer around the provided selection (unlike zoomTo, does not zoom).
Parameters
sel(AtomSelectionSpec, optional) — Selection specification specifying model and atom
properties to select. Default: all atoms in vieweranimationDuration(number, optional) — an optional parameter that denotes
the duration of the centering animation in millisecondsfixedPath(Boolean, optional) — if true animation is constrained to
requested motion, overriding updates that happen during the animation *
Example
// if the user were to pass the animationDuration value to
// the function like so viewer.zoomTo({resn:'STI'},1000);
// the program would center on resn 'STI' over the course
// of 1 second(1000 milleseconds).
// Reposition to centroid of all atoms of all models in this
//viewer glviewer.center();
$3Dmol.get('data/4csv.pdb', function(data) {
viewer.addModel(data,'pdb');
viewer.setStyle({cartoon:{},stick:{}});
viewer.center();
viewer.render(callback);
});clear(): GLViewer
Remove models, surfaces, labels, and shapes while keeping this viewer reusable.
For permanent cleanup of controls, timers, and graphics resources, use
GLViewer#destroy.
Returns
GLViewer— This viewer.
closeEnoughForClick(event: Event, options: Object)
Determine if a positioned event is "close enough" to mouseStart to be considered a click.
With a mouse, the position should be exact, but allow a slight delta for a touch interface.
Parameters
event(Event)options(Object)
createModelFrom(
sel: AtomSelectionSpec,
extract?: boolean,
): GLModel
Create a new model from atoms specified by sel.
If extract, removes selected atoms from existing models
Parameters
sel(AtomSelectionSpec) — Atom selection specificationextract(boolean, optional) — If true, remove selected atoms from existing models
Returns
destroy(): GLViewer
Permanently release this viewer's controls, timers, listeners, and graphics resources.
Repeated calls are harmless. Create a new viewer before doing further rendering or scene work.
Called automatically after removal of a previously connected container, unless autoDestroy is false.
Shared grid canvases remain until the last viewer is destroyed. A standalone
caller-supplied canvas is retained; generated canvases are removed.
Returns
GLViewer— this viewer
enableContextMenu(
sel: AtomSelectionSpec,
contextMenuEnabled: boolean,
)
enable context menu and callback of selected atoms
Parameters
sel(AtomSelectionSpec) — atom selection to apply hoverable settings tocontextMenuEnabled(boolean) — whether contextMenu-handling is enabled for the selection
enableFog(fog: boolean | FogSpec)
Enable/disable fog for content far from the camera
Parameters
fog(boolean | FogSpec) — Enable or disable fog, or provide its start and end fractions.
Example
$3Dmol.get('data/1jpy.cif', function(data) {
let m = viewer.addModel(data);
viewer.setStyle('stick');
viewer.zoomTo({resn:'NAG',chain:'B'});
viewer.enableFog({fogStart:.2,fogEnd:.6});
viewer.render();
});exportJSON(includeStyles: boolean, modelID: number): string
Export one or all of the loaded models into ChemDoodle compatible JSON.
Parameters
includeStyles(boolean) — Whether or not to include style information.modelID(number) — Optional parameter for which model to export. If left out, export all of them.
Returns
string
exportVRML(): string
return a VRML string representation of the scene. Include VRML header information
Returns
string— VRML representation.
fitSlab(sel: AtomSelectionSpec)
Adjust slab to fully enclose selection (default everything).
Parameters
sel(AtomSelectionSpec) — Selection specification specifying model and atom
properties to select. Default: all atoms in viewer
Example
$3Dmol.get('data/1jpy.cif', function(data) {
let m = viewer.addModel(data);
viewer.setStyle('stick');
viewer.zoomTo({resn:'NAG',chain:'B'});
viewer.fitSlab({resn:'NAG',chain:'B'});
viewer.render();
});getAtomsFromSel(sel: AtomSelectionSpec): Array.<AtomSpec>
Parameters
sel(AtomSelectionSpec)
Returns
Array.<AtomSpec>
getCanvas(): HTMLCanvasElement
Return underlying canvas element.
Returns
HTMLCanvasElement
getConfig(): ViewerSpec
Return the viewer's configuration object, not a copy.
Use the corresponding viewer methods to update active rendering settings;
changing this object alone does not apply every setting.
Returns
getFrame()
Gets the current viewer frame.
getInternalState(options: object)
Capture models, labels, shapes, volume grids, surfaces and display settings.
The detached result survives JSON serialization; executable callbacks are
omitted. Surfaces and isosurfaces carry their current geometry, so restoring
them does not recompute meshes or wait for surface workers.
With compact:true, model appearance is separated into modelStyles so a
classroom style edit need not resend coordinates and trajectory frames.
Parameters
options(object)
getModel(id?: number | GLModel): GLModel | null
Return specified model
Parameters
id(number | GLModel, optional) — Model or model ID. Missing or unknown IDs use the last model.
Returns
GLModel| null— The requested model, or null if there are no models.
Example
// Retrieve reference to first GLModel added var m =
$3Dmol.download("pdb:1UBQ",viewer,{},function(m1){
$3Dmol.download("pdb:1UBI", viewer,{}, function(m2) {
viewer.zoomTo();
m1.setStyle({cartoon: {color:'green'}});
//could use m2 here as well
viewer.getModel().setStyle({cartoon: {color:'blue'}});
viewer.render();
})
});getModels(): Array
Return a new array of the viewer's live models in creation order.
Removed model slots are omitted; each model retains its original getID().
Returns
Array
getNumFrames(): number
Returns the largest frame count across models and frame-specific shapes and labels.
Returns
number
getPerceivedDistance(): number
Return the z distance between the model and the camera
Returns
number— distance
getRenderer()
Return the underlying WebGL renderer.
getShape(id: number): GLShape | GLVolumetricRender | undefined
Return the shape at its shapePosition, or undefined after removal.
Parameters
id(number)
Returns
GLShape|GLVolumetricRender| undefined
getSlab(): Object
Get slab of view (contents outside of slab are clipped).
Properties
near(number) — near clipping plane distancefar(number) — far clipping plane distance
Returns
Object
getSurface(surf: number)
Return surface object
Parameters
surf(number) — surface id
getUniqueValues(
attribute: string,
sel: AtomSelectionSpec,
): Array.<string>
Returns valid values for the specified attribute in the given selection
Parameters
attribute(string)sel(AtomSelectionSpec)
Returns
Array.<string>
getView(): Array.<number>
Returns an array representing the current viewpoint.
Translation, zoom, and rotation quaternion.
Returns
Array.<number>— [ pos.x, pos.y, pos.z, rotationGroup.position.z, q.x, q.y, q.z, q.w ]
hasVolumetricRender(): boolean
Return true if volumetric rendering is supported (WebGL 2.0 required)
Returns
boolean
hideAllLabels()
Hide all labels in viewer
Example
$3Dmol.download("pdb:1ubq",viewer,{},function(){
viewer.addResLabels();
viewer.setStyle({},{stick:{}});
viewer.render( ); //show labels
viewer.hideAllLabels();
viewer.render(); //hide labels
});isAnimated(): boolean
Return true if viewer is currently being animated, false otherwise
Returns
boolean
isDestroyed(): boolean
Return true after destroy() has permanently disposed this viewer.
Returns
boolean
jmolMoveTo()
return Jmol moveto command to position this scene
linkViewer(otherviewer: GLViewer)
Link viewpoint changes from this viewer to another viewer.
This link is one-way: also call linkViewer on the other viewer for
bidirectional synchronization. Only the viewpoint is linked, not scene contents.
Parameters
otherviewer(GLViewer)
mapAtomProperties(props,: Object, sel: AtomSelectionSpec)
Add specified properties to all atoms matching input argument
Parameters
props,(Object) — either array of atom selectors with associated props, or function that takes atom and sets its propertiessel(AtomSelectionSpec) — subset of atoms to work on - model selection must be specified here
Example
$3Dmol.get('../test_structs/b.sdf', function(data){
viewer.addModel(data,'sdf');
let props = [];
//make the atom index a property x
for(let i = 0; i < 8; i++) {
props.push({index:i,props:{'x':i}});
}
viewer.mapAtomProperties(props);
viewer.setStyle({sphere:{colorscheme:{gradient:'roygb',prop:'x',min:0,max:8}}});
viewer.zoomTo();
viewer.render();
});modelToScreen(
coords: XYZ | Array.<XYZ>,
): Object | Array.<Object>
Convert model coordinates to page coordinates in pixels.
Parameters
Returns
Object | Array.<Object>— A point or list of points with x and y page coordinates, matching the input shape.
pauseAnimate()
Pause animation of all models in viewer.
An in-flight frame may finish rendering; subsequent frames wait for resumeAnimate().
pdbData(sel?: AtomSelectionSpec): string
Return the original PDB atom records saved during parsing.
Use only with atoms that have a pdbline field. The output retains original
coordinates and does not serialize later coordinate edits, bonds, or headers.
Parameters
sel(AtomSelectionSpec, optional, default: "{}") — Atoms whose original records are included.
Returns
string— Original records separated by newlines.
pngURI(): string
Return a PNG data URI of the current canvas, including all panels when
using createViewerGrid. Pending interactive redraws are flushed.
Call render() first after changing scene contents, and await asynchronous
model or surface loading before capturing its result.
Returns
string— Base64-encoded PNG data URI.
removeAllLabels()
Remove all labels from viewer
Example
$3Dmol.download("pdb:1ubq",viewer,{},function(){
viewer.addResLabels();
viewer.setStyle({},{stick:{}});
viewer.render( ); //show labels
viewer.removeAllLabels();
viewer.render(); //hide labels
});removeAllModels()
Delete all existing models
removeAllShapes()
Remove all shape objects from viewer
removeAllSurfaces()
Remove all surfaces.
removeLabel(label: Label)
Remove label from viewer
Parameters
label(Label) — $3Dmol label
Example
// Remove labels created in
$3Dmol.download("pdb:2EJ0",viewer,{},function(){
var toremove = viewer.addLabel("Aromatic", {position: {x:-6.89, y:0.75, z:0.35}, backgroundColor: 0x800080, backgroundOpacity: 0.8});
viewer.addLabel("Label",{font:'sans-serif',fontSize:18,fontColor:'white',fontOpacity:1,borderThickness:1.0,
borderColor:'red',borderOpacity:0.5,backgroundColor:'black',backgroundOpacity:0.5,
position:{x:50.0,y:0.0,z:0.0},inFront:true,showBackground:true});
viewer.removeLabel(toremove);
viewer.render();
});removeLabels(labels: Array.<Label>): GLViewer
Remove the supplied labels in one batch and redraw once. Labels not owned
by this viewer are ignored; duplicate entries are removed only once.
Parameters
labels(Array.<Label>) — labels to remove
Returns
GLViewer— this viewer
removeModel(model: GLModel | number)
Delete specified model from viewer
Parameters
model(GLModel | number)
removeShape(shape: GLShape)
Remove shape object from viewer
Parameters
shape(GLShape) — Reference to shape object to remove
removeSurface(surf: number): GLViewer
Remove surface with given ID. Unknown IDs are ignored.
Parameters
surf(number) — surface id
Returns
GLViewer— this viewer
removeUnitCell(model: GLModel | number)
Remove unit cell visualization from model.
Parameters
model(GLModel | number) — Model with unit cell information (e.g., pdb derived). If omitted uses most recently added model.
Example
$3Dmol.get('data/icsd_200866.cif', function(data) {
let m = viewer.addModel(data);
viewer.setStyle({sphere:{}})
viewer.addUnitCell();
viewer.zoomTo();
viewer.removeUnitCell();
viewer.render();
});render(callback?: function, exts?: Object): GLViewer
Rebuild and draw the current scene after adding or removing models,
changing styles, or updating interaction settings. This is synchronous;
it does not wait for downloads, frame loading, or surface computation.
Await those operations separately before rendering their completed result.
Parameters
callback(function, optional) — Called with this viewer after the draw.exts(Object, optional) — Internal renderer extension options; normally omitted.
Returns
GLViewer— This viewer, for chaining.
replicateUnitCell(
A: integer,
B: integer,
C: integer,
model: GLModel | number,
addBonds: boolean,
prune: boolean,
)
Replicate atoms in model to form a super cell of the specified dimensions.
Original cell will be centered as much as possible.
Parameters
A(integer) — number of times to replicate cell in X dimension.B(integer) — number of times to replicate cell in Y dimension. If absent, X value is used.C(integer) — number of times to replicate cell in Z dimension. If absent, Y value is used.model(GLModel | number) — Model with unit cell information (e.g., pdb derived). If omitted uses most recently added model.addBonds(boolean) — Create bonds between unit cells based on distances.prune(boolean) — Keep only atoms that are within the original unit cell (i.e., on edges). Alternatively, call replicateUnitCell(1).
Example
$3Dmol.get('data/icsd_200866.cif', function(data) {
let m = viewer.addModel(data);
viewer.setStyle({sphere:{scale:.25}})
viewer.addUnitCell();
viewer.zoomTo();
viewer.replicateUnitCell(3,2,1,m);
viewer.render();
});resize()
Resize viewer according to containing HTML element's dimensions
resumeAnimate()
Resume animation of all models in viewer
rotate(
angle?: number,
axis?: string,
animationDuration?: number,
fixedPath?: boolean,
)
Rotate scene by angle degrees around axis
Parameters
angle(number, optional) — Angle, in degrees, to rotate by.axis(string, optional) — Axis ("x", "y", "z", "vx", "vy", or "vz") to rotate around.
Default "y". View relative (rather than model relative) axes are prefixed with v.
Axis can also be specified as a vector.animationDuration(number, optional) — an optional parameter that denotes
the duration of the rotation animation in milliseconds. Default 0 (no animation)fixedPath(boolean, optional) — if true animation is constrained to
requested motion, overriding updates that happen during the animation *
Example
$3Dmol.download('cid:4000', viewer, {}, function() {
viewer.setStyle({stick:{}});
viewer.zoomTo();
viewer.rotate(90,'y',1);
viewer.render(callback);
});screenOffsetToModel(
x: number,
y: number,
modelz?: number,
): Vector3
For a given screen (x,y) displacement return model displacement
Parameters
x(number) — Horizontal displacement in pixels.y(number) — Vertical displacement in pixels.modelz(number, optional) — Depth at which to compute the offset; defaults to the rotation group depth.
Returns
Vector3— Model displacement.
screenToModelDistance(screen: Object, model: XYZ): number
Distance from screen coordinate to model coordinate assuming screen point
is projected to the same depth as model coordinate
Parameters
screen(Object) — Point with x and y page coordinates in pixels.model(XYZ) — Point in model coordinates.
Returns
number— Distance in model units.
selectedAtoms(sel?: AtomSelectionSpec): Array.<AtomSpec>
Return atoms matching a selection across the selected models.
Selection is evaluated separately in each model; distance-based selectors
such as within do not search other models. Returned atoms are live model
objects, not copies.
Parameters
sel(AtomSelectionSpec, optional, default: "{}") — Selection; omitted selects all atoms.
Returns
Array.<AtomSpec>— Matching atoms from the models' current frames.
setAutoEyeSeparation(isright: boolean, x: number): number
Used for setting an approx value of eyeSeparation. Created for calling by StereoViewer object
Parameters
isright(boolean)x(number)
Returns
number— camera x position
setBackgroundColor(hex: ColorSpec, a: number)
Set the background color (default white)
Parameters
hex(ColorSpec) — Hexcode specified background color, or standard color speca(number) — Alpha level (default 1.0)
Example
viewer.setBackgroundColor("green",0.5);setCameraParameters(parameters: Object)
Update camera distance, field of view, or projection mode.
Omitted fields retain their values. Field of view is in degrees, and z is
in model units. Call render() to display the change.
Parameters
parameters(Object) — new camera parameters, with possible fields
being fov for the field of view, z for the
distance to the origin, and orthographic (boolean)
for kind of projection (default false).
Example
$3Dmol.get("data/set1_122_complex.mol2", function(data) {
var m = viewer.addModel(data);
viewer.setStyle({stick:{}});
viewer.zoomTo();
viewer.setCameraParameters({ fov: 10 , z: 300 });
viewer.render();
});setClickable(
sel: AtomSelectionSpec,
clickable: boolean,
callback: function,
)
Set click-handling properties to all selected atoms. Important: render must be called for this to take effect.
Parameters
sel(AtomSelectionSpec) — atom selection to apply clickable settings toclickable(boolean) — whether click-handling is enabled for the selectioncallback(function) — function called when an atom in the selection is clicked. The function is passed
the selected (foremost) object, the viewer, the triggering event, the associated container, and a list
of all intersecting objects with their distances from the viewer.
Example
$3Dmol.download("cid:307900",viewer,{},function(){
viewer.setStyle({},{sphere:{}});
viewer.setClickable({},true,function(atom,viewer,event,container) {
viewer.addLabel(atom.resn+":"+atom.atom,{position: atom, backgroundColor: 'darkgreen', backgroundOpacity: 0.8});
});
viewer.render();
});setColorByElement(sel: AtomSelectionSpec, colors: object)
Parameters
sel(AtomSelectionSpec)colors(object)
setColorByProperty(
sel: AtomSelectionSpec,
prop: string,
scheme: Gradient | string,
range: object,
)
Parameters
sel(AtomSelectionSpec)prop(string)scheme(Gradient | string)range(object)
setConfig(c: ViewerSpec)
Replace the stored configuration object. This does not merge with the
previous configuration or reinitialize the viewer. Ambient occlusion is
applied immediately when supplied; use dedicated setters for other live
changes. Many ViewerSpec settings are read only during creation.
Parameters
c(ViewerSpec) — Replacement configuration.
setContainer(element: Object | string)
Change the viewer's container element
Moves before automatic removal cleanup runs preserve the viewer. Set autoDestroy
to false when retaining a detached viewer for later reuse. A detached new container
is allowed and is monitored for removal after its first attachment.
Parameters
element(Object | string) — Either HTML element or string identifier. Defaults to the current container.
setDefaultCartoonQuality(val: number)
Set the default cartoon quality for newly created models. Default is 10.
Current models are not affected.
Parameters
val(number) — Quality; higher values increase rendering resolution.
setFrame(framenum: number, options: Object): Promise.<void>
Sets the atomlists of all models in the viewer to specified frame.
Shapes and labels can also be displayed by frame.
Indices wrap modulo the viewer's total frame count, so -1 selects its last
frame. Models, shapes and labels receive that resolved frame; models with
fewer frames wrap it to their own frame count. Fractional indices truncate
toward zero; non-finite values use frame zero.
The viewer's frame number updates immediately; await the returned promise
before rendering frames that require asynchronous loading.
Parameters
framenum(number) — frame index to use, starts at zerooptions(Object) — {fast: true} replays the frame's coordinates into each model's
existing geometry instead of rebuilding it (see GLModel.setFrame); off by default.
Without fast, this refreshes geometry even when the selected frame has not changed.
Returns
Promise.<void>— Resolves when all models have selected or loaded the frame.
Example
Await the selected frame before drawing frame-specific labels.
var pdb = [
"MODEL 1",
"HETATM 1 C1 LIG A 1 -0.600 -1.500 0.000 1.00 0.00 C",
"HETATM 2 O1 LIG A 1 0.600 -1.500 0.000 1.00 0.00 O",
"ENDMDL",
"MODEL 2",
"HETATM 1 C1 LIG A 1 -0.600 1.500 0.000 1.00 0.00 C",
"HETATM 2 O1 LIG A 1 0.600 1.500 0.000 1.00 0.00 O",
"ENDMDL"
].join("\n");
viewer.addModelsAsFrames(pdb, "pdb");
viewer.setStyle({}, {stick: {radius: 0.25}, sphere: {scale: 0.3}});
viewer.addLabel("Frame 0", {
frame: 0, useScreen: true, position: {x: 12, y: 20, z: 0},
fontColor: "black", showBackground: false
});
viewer.addLabel("Frame 1 (selected with -1)", {
frame: 1, useScreen: true, position: {x: 12, y: 20, z: 0},
fontColor: "black", showBackground: false
});
(async function () {
await viewer.setFrame(-1);
viewer.zoomTo();
viewer.render();
})();setHeight(h: number)
Set the canvas height independently of the HTML container. This is probably not what you want.
For responsive layouts, size the container with CSS and use GLViewer#resize.
Parameters
h(number) — Height in pixels
setHoverDuration(duration: number)
Set the delay before an atom's hover callback runs.
The initial viewer delay is 500 milliseconds unless configured otherwise.
Parameters
duration(number) — Hover delay in milliseconds.
setHoverable(
sel: AtomSelectionSpec,
hoverable: boolean,
hover_callback: function,
unhover_callback: function,
)
Set hover handling for selected atoms. Call render() to update hit testing.
Parameters
sel(AtomSelectionSpec) — atom selection to apply hoverable settings tohoverable(boolean) — whether hover-handling is enabled for the selectionhover_callback(function) — function called when an atom in the selection is hovered over. The function has the same signature as a click handler.unhover_callback(function) — function called when the mouse moves out of the hover area
Example
$3Dmol.download("pdb:1ubq",viewer,{},function(){
viewer.setHoverable({},true,function(atom,viewer,event,container) {
if(!atom.label) {
atom.label = viewer.addLabel(atom.resn+":"+atom.atom,{position: atom, backgroundColor: 'mintcream', fontColor:'black'});
}
},
function(atom,viewer) {
if(atom.label) {
viewer.removeLabel(atom.label);
delete atom.label;
}
}
);
viewer.setStyle({},{stick:{}});
viewer.render();
});setInternalState(state, options: object)
Restore a scene snapshot. partial:true replaces only the supplied sections.
Models and materialized geometry are installed synchronously. Omitted
sections in a full snapshot are cleared, including old model-only snapshots.
Callback source strings are never restored or evaluated.
Parameters
stateoptions(object)
setLabelStyle(label: Label, stylespec: LabelSpec): Label
Modify existing label's style
Parameters
Returns
setLabelText(label: Label, text: String): Label
Modify existing label's text
Parameters
label(Label) — $3Dmol labeltext(String) — Label text
Returns
setPerceivedDistance(dist: number)
Set the distance between the model and the camera
Essentially zooming. Useful while stereo rendering.
Parameters
dist(number)
setProjection(proj)
Set view projection scheme. Either orthographic or perspective.
Default is perspective. Orthographic can also be enabled on viewer creation
by setting orthographic to true in the config object.
Parameters
proj
Example
viewer.setViewStyle({style:"outline"});
$3Dmol.get('data/1fas.pqr', function(data){
viewer.addModel(data, "pqr");
$3Dmol.get("data/1fas.cube",function(volumedata){
viewer.addSurface($3Dmol.SurfaceType.VDW, {opacity:0.85,voldata: new $3Dmol.VolumeData(volumedata, "cube"), volscheme: new $3Dmol.Gradient.RWB(-10,10)},{});
});
viewer.zoomTo();
viewer.setProjection("orthographic");
viewer.render(callback);
});setSlab(near: number, far: number)
Set slab of view (contents outside of slab are clipped).
Must call render to update.
Parameters
near(number) — near clipping plane distancefar(number) — far clipping plane distance
setStateChangeCallback(callback: function | null)
Set a callback called by render() with the current internal state.
Parameters
callback(function | null) — Receives the object returned by getInternalState(); null clears the callback.
setStyle(sel: AtomSelectionSpec, style: AtomStyleSpec)
Replace all style properties on selected atoms. Styles on unselected
atoms are unchanged. Pass an empty style object to hide the selection,
or use GLViewer#addStyle to preserve existing representations.
With one argument, that argument is a style applied to all atoms.
Call render() to display the change.
Parameters
sel(AtomSelectionSpec) — Atom selection specification. Can be omitted to select all.style(AtomStyleSpec) — Style spec to apply to specified atoms
Example
viewer.setBackgroundColor(0xffffffff);
$3Dmol.download('pdb:5IRE',viewer,{doAssembly: false},function(m) {
m.setStyle({chain:'A'},{'cartoon':{color:'spectrum'}});
m.setStyle({chain:'C'},{'cartoon':{style:'trace',color:'blue'}});
m.setStyle({chain:'E'},{'cartoon':{tubes:true,arrows:true,color:'green',opacity:0.75}});
m.setStyle({chain:'B'},{'cartoon':{color:'red',opacity:0.5}});
m.setStyle({chain:'D'},{'cartoon':{style:'trace',color:'grey',opacity:0.75}});
m.setStyle({chain:'F'},{'cartoon':{arrows:true,color:'white'}});
// viewer.addStyle({chain:'B'},{line:{}});
viewer.zoomTo();
viewer.render();
});setSurfaceMaterialStyle(surf: number, style: SurfaceStyleSpec)
Set the surface material to something else, must render change
Parameters
surf(number) — Surface ID to apply changes tostyle(SurfaceStyleSpec) — new material style specification
Example
$3Dmol.get("data/9002806.cif",function(data){
viewer.addModel(data);
viewer.setStyle({stick:{}});
let surf = viewer.addSurface("SAS");
surf.then(function() {
viewer.setSurfaceMaterialStyle(surf.surfid, {color:'blue',opacity:0.5});
viewer.render();
});
});setView(arg: Array.<number>, nolink?: boolean): GLViewer
Restore translation, zoom, and rotation from GLViewer#getView.
Invalid arrays are ignored. This restores the viewpoint only, not models,
styles, projection settings, or clipping planes.
Parameters
arg(Array.<number>) — Eight finite numbers in getView() order. A legacy
ten-number array may append the rotation group's x and y translation.nolink(boolean, optional, default: false) — Suppress updates to linked viewers.
Returns
GLViewer— This viewer.
setViewChangeCallback(callback: function | null)
Set a callback to call when the view has potentially changed.
Mouse/touch redraws are coalesced to display frames, except for linked viewers;
the callback runs after each draw, rather than after every input event.
Parameters
callback(function | null) — Receives the array returned by getView(); null clears the callback.
setViewStyle(parameters: ViewStyle)
Set global view styles.
Parameters
parameters(ViewStyle)
Example
viewer.setViewStyle({style:"outline"});
$3Dmol.get('data/1fas.pqr', function(data){
viewer.addModel(data, "pqr");
$3Dmol.get("data/1fas.cube",function(volumedata){
viewer.addSurface($3Dmol.SurfaceType.VDW, {opacity:0.85,voldata: new $3Dmol.VolumeData(volumedata, "cube"), volscheme: new $3Dmol.Gradient.RWB(-10,10)},{});
});
viewer.zoomTo();
viewer.render(callback);
});setWidth(w: number)
Set the canvas width independently of the HTML container. This is probably not what you want.
For responsive layouts, size the container with CSS and use GLViewer#resize.
Parameters
w(number) — Width in pixels
setZoomLimits(lower?: number, upper?: number)
Set lower and upper limit stops for zoom.
Limits are camera-to-model distances in model units. Omitted arguments
retain the current limits; a new viewer has no zoom limits.
Parameters
lower(number, optional) — Minimum distance (zoom-in limit). Zero disables this limit.upper(number, optional) — Positive maximum distance (zoom-out limit).
Example
$3Dmol.get("data/set1_122_complex.mol2", function(moldata) {
var m = viewer.addModel(moldata);
viewer.setStyle({stick:{colorscheme:"Jmol"}});
viewer.setZoomLimits(100,200);
viewer.zoomTo();
viewer.zoom(10); //will not zoom all the way
viewer.render();
});showAllLabels()
Show all labels in viewer
Example
$3Dmol.download("pdb:1ubq",viewer,{},function(){
viewer.addLabel("Hello World",{position:{x:10,y:0,z:0},backgroundColor: "blue",useScreen: true, fontSize: 64})
viewer.setStyle({},{stick:{}});
viewer.render( ); //show labels
viewer.hideAllLabels();
viewer.showAllLabels();
viewer.render(); //hide labels
});spin(
axis: string | boolean | Array,
speed: number,
only_when_visable: boolean,
)
Continuously rotate a scene around the specified axis.
Call spin(false) to stop spinning.
Parameters
axis(string | boolean | Array) — [axis] - Axis ("x", "y", "z", "vx", "vy", or "vz") to rotate around.
Default "y". View relative (rather than model relative) axes are prefixed with v.speed(number) — [speed] - Speed multiplier for spinning the viewer. 1 is default and a negative
value reverses the direction of the spin.only_when_visable(boolean) — [only_when_visable] - if true, will only update spin when canvas is visible
stopAnimate()
Stop animation of all models in viewer.
Camera motions continue and remain included in isAnimated().
Pending frame loads are not aborted, but cannot restart a stopped animation.
subscribeStateChanges(): function
Subscribe to scene renders without eagerly serializing the scene.
Returns an unsubscribe function. Camera-only draws do not notify listeners.
Returns
function
targetedObjects(
x: number,
y: number,
objects: Array.<Object> | AtomSelectionSpec,
): Array.<Object>
Return intersection records for objects at the specified normalized viewer position.
Parameters
x(number) — Normalized horizontal coordinate: -1 at the left edge, +1 at the right edge.y(number) — Normalized vertical coordinate: -1 at the bottom edge, +1 at the top edge.objects(Array.<Object> | AtomSelectionSpec) — Objects to test, or an atom selection.
Returns
Array.<Object>— Intersection records sorted by distance, nearest first.
translate(
x: number,
y: number,
animationDuration?: number,
fixedPath?: Boolean,
)
Translate current view by x,y screen coordinates
This pans the camera rather than translating the model.
Parameters
x(number) — Relative change in view coordinates of cameray(number) — Relative change in view coordinates of cameraanimationDuration(number, optional) — an optional parameter that denotes
the duration of the translation animation in millisecondsfixedPath(Boolean, optional) — if true animation is constrained to
requested motion, overriding updates that happen during the animation *
Example
$3Dmol.get('data/4csv.pdb', function(data) {
viewer.addModel(data,'pdb');
viewer.setStyle({cartoon:{},stick:{}});
viewer.zoomTo();
viewer.translate(200,50);
viewer.rotate(90,'z');
viewer.render(callback);
});translateScene(
x: number,
y: number,
animationDuration?: number,
fixedPath?: Boolean,
)
Translate current models by x,y screen coordinates
This translates the models relative to the current view. It does
not change the center of rotation.
Parameters
x(number) — Relative change in x screen coordinatey(number) — Relative change in y screen coordinateanimationDuration(number, optional) — an optional parameter that denotes
the duration of the translation animation in millisecondsfixedPath(Boolean, optional) — if true animation is constrained to
requested motion, overriding updates that happen during the animation *
Example
$3Dmol.get('data/4csv.pdb', function(data) {
viewer.addModel(data,'pdb');
viewer.setStyle({cartoon:{},stick:{}});
viewer.zoomTo();
viewer.translateScene(200,50);
viewer.rotate(90,'z'); // will no longer be around model center
viewer.render(callback);
});vibrate(
numFrames: number,
amplitude: number,
bothways: boolean,
arrowSpec: ArrowSpec,
)
If atoms have dx, dy, dz properties (in some xyz files), vibrate populates each model's frame property based on parameters.
Models can then be animated
Parameters
numFrames(number) — number of frames to be created, default to 10amplitude(number) — amplitude of distortion, default to 1 (full)bothways(boolean) — if true, extend both in positive and negative directions by numFramesarrowSpec(ArrowSpec) — specification for drawing animated arrows. If color isn't specified, atom color (sphere, stick, line preference) is used.
zoom(
factor?: number,
animationDuration?: number,
fixedPath?: Boolean,
)
Zoom current view by a constant factor
Parameters
factor(number, optional) — Magnification factor. Values greater than 1
will zoom in, less than one will zoom out. Default 2.animationDuration(number, optional) — an optional parameter that denotes
the duration of a zoom animationfixedPath(Boolean, optional) — if true animation is constrained to
requested motion, overriding updates that happen during the animation
Example
$3Dmol.get('data/4csv.pdb', function(data) {
viewer.addModel(data,'pdb');
viewer.setStyle({cartoon:{},stick:{}});
viewer.zoomTo()
viewer.zoom(2,1000);
viewer.render();
});zoomTo(
sel?: AtomSelectionSpec,
animationDuration?: number,
fixedPath?: Boolean,
)
Zoom to the center of an atom selection and adjust the clipping slab to include all atoms.
An empty selection object selects the whole scene, including shapes, and uses a wider finite slab.
Parameters
sel(AtomSelectionSpec, optional) — Selection specification specifying model and atom
properties to select. Default: all atoms in vieweranimationDuration(number, optional) — an optional parameter that denotes
the duration of a zoom animationfixedPath(Boolean, optional) — if true animation is constrained to
requested motion, overriding updates that happen during the animation *
Example
$3Dmol.get('data/1fas.pqr', function(data){
viewer.addModel(data, "pqr");
viewer.zoomTo();
$3Dmol.get("data/1fas.cube",function(volumedata){
viewer.addSurface($3Dmol.SurfaceType.VDW, {
opacity:0.85,
voldata: new $3Dmol.VolumeData(volumedata, "cube"),
volscheme: new $3Dmol.Gradient.Sinebow($3Dmol.getPropertyRange(viewer.selectedAtoms(),'charge'))
},{});
viewer.render();
});
});Static Methods
generateMeshSyncHelper(
type: SurfaceType,
expandedExtent: Array,
extendedAtoms: Array.<AtomSpec>,
atomsToShow: Array.<AtomSpec>,
atoms: Array.<AtomSpec>,
vol: number,
): Object
Parameters
type(SurfaceType)expandedExtent(Array)extendedAtoms(Array.<AtomSpec>)atomsToShow(Array.<AtomSpec>)atoms(Array.<AtomSpec>)vol(number)
Returns
Object
generateSurfaceMesh(
atoms: Array.<AtomSpec>,
VandF: Object,
mat: MeshLambertMaterial,
): Mesh
Parameters
atoms(Array.<AtomSpec>)VandF(Object)mat(MeshLambertMaterial)
Returns
Mesh
getAtomsWithin(atomlist: Array.<AtomSpec>, extent: Array): Array
Parameters
atomlist(Array.<AtomSpec>)extent(Array)
Returns
Array
Instance Fields
ui: StateManager
Optional controls, installed by the separate 3Dmol.ui bundle.
userContextMenuHandler: function | null
User specified function for handling a context menu event.
Handler is passed the selected object, x and y in canvas coordinates,
and original event.