livereference.org

scene3d

3D interactive graphics plugin for jQuery

$(function() { var myCanvas = $('#3dcanvas').scene3d(); myCanvas.addBox(); }); ... <div id="3dcanvas"></div>
get it from

3D - clear and simple

left click and move; wheel to zoom;

Plugin documentation

scene3d is 3D interactive graphics jQuery plugin based on HTML5 and X3DOM. It allows rapid and effortless prototyping of 3D scenes for web.

1. Quick Start

1.1. Graphics Scene

<div id="my-3D-scene"></div>

Your graphics "scene" will be placed inside a <div> element. You can place it anywhere on the page and make it any size. However, inside the scene, the <div> position and dimensions are not applicable any more. The scene lives inside its own world, with its own coordinate system and its own units of measurements.

Root of a 3D scene is always in the centre at the position x=0, y=0, z=0. An object position is defined by (x y z) coordinates relative to the main scene. Forget about pixels - distances are measured in meters ( 1m=39.3” ) and angles in radians ( =degrees * 3.14/180 ) )

Like in a movie set, the scene is viewed by a "camera" which you can place anywhere in the scene (see the picture). If not explicitly defined, camera will be placed 10m up the z axis at the position (0 0 10) which will be your viewpoint of the scene.

In addition to the position, you can also specify camera rotation. Since this is a bit more advanced topic, if interested, you can find more about it in the advanced topics section.

1.2. HTML page template

<!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="chrome=1" /> <meta charset="utf-8"> <title>scene3d template</title> <!-- include your x3dom, jquery and scene3d scripts --> <script src="http://www.x3dom.org/download/x3dom.js"></script> <link rel='stylesheet' type='text/css' href='http://www.x3dom.org/download/x3dom.css'/> <script src="http://code.jquery.com/jquery-latest.js"></script> <script src="scene3d.jquery.js"></script> <script> $(function() { var myCanvas = $('#3dcanvas').scene3d(); // initialize your canvas myCanvas.addBox(); // draw a box }); </script> </head> <body> <!-- my canvas --> <div id="3dcanvas"></div> </body> </html>

2. Plugin options

scene3d can be initialized with a number of options, for example: var myCanvas = $('#3dcanvas').scene3d({ width: "320px", // canvas width (default is 150px) height: "320px", // canvas height (default is 150px) });

The following table shows the list of available options:

OptionDefault valueDescription
background'#ffffff'RGB hex string
backurl'''path to background image
fontFamily'Sans'font family name
fontSize0.5relative font size
height'150px'canvas height in pixels
id'x3dElement'x3d DOM id
sceneAnimationfalserealtime scene rotation (heavy on CPU)
showLogfalseshow x3dom log (for debugging)
showStatfalseshow realtime graphics statistics
ViewpointPosition'0 0 10'camera position relative to (0,0,0).
Default viewpoint position is (0 0 10) meaning that the camera is placed on the same level as x and y axis and 10m on z axis or backwards/south from the 0,0,0 point.
ViewpointOrientation'0 0 0 1''x y z angle' The first three values specify a normalized rotation axis vector about which the rotation takes place. The fourth value specifies the amount of right-handed rotation about that axis in radians.
Note: More about this you can find in the advanced topics section.

back to contents

3. Graphics objects

Graphics objects include: box,cone, cylinder, line, sphere, text and complex graphs. Any of the objects can be created with a single command. For example, to initialize a canvas and add a box into drawing, you can simply type: var myCanvas = $('#3dcanvas').scene3d(); myCanvas.addBox();

3.1. Creating Objects

Graphics objects can be created by calling number of methods and specifying objects attributes as shown in the following table:

MethodOption list
with default options
Description
addBox addBox({ id: null, x:0, y:0, z:0, width:1, depth:1, height:1, color:'#eeeeee', label:'', labeloffset:.1, fontFamily:'Sans', fontColor:'#000000', fontSize:0.5 )} Draw a box with selected properties. If property is omitted or none is specified, it will use defaults. Example: myCanvas.addBox({ x:0, y:0, label: 'this is my box' });
addCone addCone({ id: null, x:0, y:0, z:0, height:1, bottomRadius:1.0, topRadius:0, color:'#eeeeee', label:'', labeloffset:.1, fontFamily:'Sans', fontColor:'#000000', fontSize:0.5 }) Draw a cone with selected properties. If property is omitted or none is specified, it will use defaults. Example: myCanvas.addCone({ x:0, y:0, z:0, height:1.5 });
addCylinder addCylinder({ id: null, x:0, y:0, z:0, radius: 1, height:1, color:'#eeeeee', label:'', labeloffset:.1, fontFamily:'Sans', fontColor:'#000000', fontSize:0.5 }) Draw a cylinder with selected properties. If property is omitted or none is specified, it will use defaults. Example: myCanvas.addCylinder({ x:0, y:0, z:0, radius:.5 });
addGraph addGraph({ data: myGraph, width: 10, height: 4, depth: 10 });

A graph consists of set of vertices and edges connecting them. It is drawn as spheres and lines connecting them. The graph data structure is a JSON object.
More about graphs in the Graphs section.

addLine addLine({ id: null, x1:0, y1:0, z1:0, x2:1, y2:1, z2:1, linewidth:1, linetype:1, color: '#eeeeee', label:'', labeloffset: 0.1, fontFamily:'Sans', fontColor:'#000000', fontSize:0.5 }) Draws a line with selected properties from (x1,y1,z1) to (x2,y2,z2). If property is omitted or none is specified, it will use defaults. For example, to draw a coordinate system one can use: myCanvas.addLine( { x1:-4,x2:4 } ); myCanvas.addLine( { y1:-4,y2:4 } ); myCanvas.addLine( { z1:-4,z2:4 } ) Possible linetypes: 1 Solid, 2 Dashed, 3 Dotted, 4 Dashed-dotted, 5 Dash-dot-dot. However, the parameter 'linetype' is still not supported by many browsers and they will simply draw a solid line. For the future linetype reference, please have a look at web3d.org standard
addSphere addSphere({ id: null, onclick: null, x:0, y:0, z:0, radius: 1, color:'#eeeeee', label:'', labeloffset:.1, fontFamily:'Sans', fontColor:'#000000', fontSize:0.5 }) Draw a sphere with selected properties. If property is omitted or none is specified, it will use defaults. Example: myCanvas.addSphere();
addText addText({ id: null, x:0, y:0, z:0, label:'', fontFamily:'Sans', fontColor:'#000000', fontSize:0.5 }) Draw a text with selected properties. If property is omitted or none is specified, it will use defaults. myCanvas.addText({ fontColor:'#0000ff' label:'My 3D drawing title' });
removeShape myCanvas.removeShape( id ); Removes shape of a given id from the canvas $('#remove').on('click', function () { myCanvas.removeShape ( '#mySphere' ); }); ... ... <button id='remove'>remove sphere</button>
importX3D myCanvas.importX3D({ x:0, y:0, z:0, url:'<x3d_object_url>' }); Imports x3d object to your canvas. This allows you to have an reusable library of different shapes and drawings. myCanvas.importX3D({ x:1, y:2, z:3, url:'libx3d/cola_can.x3d' });

back to contents

3.2. Clickable Shapes

Each shape can be initialized with two more options: click handler name and HTML5 "data-" attribute. The "data-" attribute can contain any string, and can have any name - as long as starts with "data-". For example, we can attach a click event to a sphere:

myCanvas.addSphere ({ x:1.2, y:0, z:2, radius:1, color:'#ff00ff', id:'mySphere', onclick:'sphereClickHandler(this)', 'data-description':'This is my sphere!' }); sphereClickHandler = function( gObj ) { alert ( $(gObj).data('description') ); }

Please note that the attribute 'data-description' must be quoted. To retrieve the content of this attribute, simply use jQuery .data() method. If you wish to attach more complex information, a database record for example, you can retrieve a sphere id ($(gObj).attr('id')) and make an ajax call to your database to retrieve and display the desired record.

back to contents

4. Graphs

A graph consists of set of nodes and edges connecting them. In the simplest form, a graph can be created with a single command. The following example shows names (nodes) of Hollywood actors linked by movies (edges) they were acting together:

myCanvas.addGraph({ data: myGraph, width: 10, height: 4, depth: 10 });

The information about nodes (actors) and edges (movies) is obtained from a variable called myGraph. This variable is a JSON object that can be hard coded, generated by a script, or loaded from a file or a database via an ajax call.

 

4.1. Preparing graph data

In it's textual form a graph is represented in JSON (JavaScript Object Notation) object consisting of attribute-value pairs. The attribute is a keyword that cannot be changed, but the value can be any text. Both, an attribute and a value must be inclosed in a quotation marks. In our example JSON is as follows:

{ "node": [ { "id": "n1", "label": "Brad Pitt" }, { "id": "n2", "label": "Angelina Jolie" } ], "edge": [ { "source": "n1", "target": "n2", "label": "Mr. & Mrs. Smith", } ] }

Notice that each node has an unique id which is used to define edges between nodes. This JSON object can be saved as a actors.json file and drawn with a few lines of code:

$.getJSON( "actors.json", function( graph ) { myCanvas.drawGraph( { data: graph }); });

The following table shows all JSON attributes recognized by drawGraph function. The minimum attributes required is "id" for nodes and "source" and "target" ids for edges. Labels, coordinates, colors etc. are optional and if not given, it will be assigned automatically.

{ "node": [ { "id": "n1", "label": "Brad Pitt" }, { "id": "n2", "label": "Angelina Jolie", "x": 10, "y": 15, "z": 15, "radius": 2, "color": "#ff0000", "fontFamily": "Arial", "fontColor": "#224466", "fontSize": 0.5 } ], "edge": [ { "source": "n1", "target": "n2", "label": "Mr. & Mrs. Smith", "linewidth": 1, "color": "#0000ff", "fontFamily": "Arial", "fontColor": "#224466", "fontSize": 0.5 } ] }

For function to work properly the JSON structure must have a valid format. If not familiar with JSON, you can use online tools to generate, or just to validate your JSON data.

back to contents

4.2. Graph options

The minimal information you need for a graph is just to specify where the graph data is. However, addGraph method accepts a rich set of options:

myCanvas.addGraph({ data: myGraph, layout: 'random', // 'cuboid' or 'forcedirected' forcedirected: { maxIterations: 100, // when to stop animation k: 300, // Hooke's law spring attraction constant ke: 200, //Coulomb's repulsion constant mass: 5, // node mass slength: 1, // spring length timetick: 50, // animation interval timestep: 0.05, damping: 0.5 // damping constant } radius: 0.1, // node radius linewidth: 1, color:'#eeeeee', // node color labeloffset:.1, // how far from node fontFamily:'Sans', fontColor:'#000000', fontSize:0.5 width: 10, // canvas dimensions height: 4, // in x3d units depth: 10 });

The following options: radius, linewidth, color, fontFamily, fontColor, fontSize will be ignored if the same attributes exists in your JSON object. It will be used as a fallback data if a node or a edge does not have specific requirement for a color, font, etc...

It is possible to draw three types of layouts:

back to contents

4.3. Enriching your graphs

Graphs can be enriched with additional data by using HTML5 "data-" attribute. Data can be displayed to the user by attaching click handlers to nodes or edges. In the following example we added attributes "data-bio" to nodes and "data-movie" to edges. As specified in HTML5 any attribute that starts with "data-" can carry data and can be included in a graph.

{ "node": [ { "id": "n1", "label": "Brad Pitt" }, { "id": "n2", "label": "Angelina Jolie", "data-bio": "born in Shawnee, Oklahoma", "onclick": "nodeClickHandler(this)", } ], "edge": [ { "source": "n1", "target": "n2", "label": "Mr. & Mrs. Smith", "data-movie": "2005 American romantic comedy action film.", "onclick": "edgeClickHandler(this)", } ] }

Only few lines of code is needed to display this graph:

$.getJSON( "actors.json", function( graph ) { myCanvas.drawGraph( { data: graph } ); }); nodeClickHandler = function( gObj ) { alert ( $(gObj).data('bio') ); } edgeClickHandler = function( gObj ) { alert ( $(gObj).data('movie') ); }

If you wish to retrieve more complex information, a database record for example, you can use "data-" or "id" attribute as a database key and make an ajax call to your database to fetch a desired record.

edgeClickHandler = function( gObj ) { $.get( "ajax/dbFetch.php", { movie: $(gObj).data('movie') }, function( movieData ) { alert (movieData); }); }

back to contents

6. Advanced topics

6. Camera rotation

In addition to the position (as described in 1.1. Graphics Scene section), you can specify the camera rotation by four values: (x y z angle). This settings is called ViewpointOrientation and corresponds to a SFRotation field in the X3D standard specification.

The first three values specify a normalized (having values between 0 and 1) rotation axis vector about which the rotation takes place. The fourth value specifies the amount of rotation.

Imagine someone taking a "selfie" as shown in the picture. The center of a local coordinate system (0 0 0) can be placed in the root of the right arm that will act as an axis vector about which hand can rotate the camera. Since we are interested in the vector direction and the rotation angle only, the length of this vector is not important. We'll use the length of 1 so the coordinates of the vector's endpoint will be our normalized values of the rotation axis.

Finally, the rotation angle is determined by rotation of the right hand holding the camera.
(Formally, the right hand rule is applied - right hand grabs the vector while thumb points in the same direction as the arrow and rotation angle is measured.)

For example, if you wish to rotate camera 45 degrees (0.785 radians) around x axis only, the rotation will be defined as (1 0 0 0.785). Similarly, the rotation around y and z axes will be (0 1 0 0.785) and (0 0 1 0.785) respectively.

There is even more than it meets the eye. For example, the system gets its final rotation axis by comparing coordinates of the local axis with the origin of it's parent coordinate system, but this is beyond the scope of this manual.

back to contents

6. Examples

Click here for minimal, bare-bone examples so that you can clearly see what’s going on. View the source (right-click on the page and select "View Page Source").

back to contents

6. Download

All you need is two files. Simply right click on the link below and "Save as"

or vist me at

If you dont't have the latest jQuery and x3dom, you can get them here:

back to contents

Contents