News Examples Documentation Download Buy Forum Contact

krpano Javascript Interface Version 1.22

To get access to krpano from Javascript the krpano Interface Object is required.
This interface can be used to access and control everything inside the krpano viewer.

Entry Point - Getting the krpano Interface Object

The best and recommend way for getting the krpano Interface Object would be using the onready callback from the embedpano() function:
embedpano({..., onready:function(krpano) {     console.log( krpano.version ); });

Another way would be using document.getElementById(id) with the id that was set set in the embedpano() call:
embedpano({..., id:"mypano"}); ... var krpano = document.getElementById("mypano"); console.log( krpano.version );
However, this way would not be recommended - depending on your code/application structure, the embedpano() may not have been called yet when getElementById() is used for the first time.

Additionally the krpano Interface Object is also available in:

krpano Interface Object

The krpano Interface Object is the direct interface to krpano. It provides direct access to the whole krpano structure and all variables/settings and functions there. All xml nodes and attributes are also mapped there.
Base/Core Interface Functions: (Legacy Interface) Advanced Functions: Extension Functions: Event Functions: krpano Actions with their direct Javascript API: Loading: Special Path-Parsing / Loading Interception: Coordinate Conversion Functions: Reactive Programming: Expression Functions Direct Access to the Data-Structure Predefined krpano Arrays: Base Object API: Array Object API: WebGL API:

krpano.set(variable, value)
  • Sets a variable to a given value.
  • If the variable or the path to it doesn't exist, then the variable and path will be created.
  • Works like the set() action.

result = krpano.get(variable)
  • Returns the value of a variable.
  • Returns null if the variable doesn't exist.

krpano.call(actionscode, caller*)
  • Call krpano action code.
    • When the actions system is currently not blocked (e.g. due xml-loading or xml-parsing), then the actions will be directly executed.
    • But when blocked, the actions will be 'queued' and automatically executed once the actions system is unblocked again.
  • actionscode = a String with one or more krpano actions.
  • caller (optionally)
    • The 'caller' of the action code.
    • This is an Object that will be used as local variable scope.
    • This allows direct access to the attributes of that Object.

krpano.trace(code, message)
  • Trace out messages to the krpano log.
  • code = numeric code of the message-type:
    • 0 = DEBUG message (these will be only shown with enabled debugmode)
    • 1 = INFO message
    • 2 = WARNING message
    • 3 = ERROR message (when showerrors is enabled, the log will also be opened)
    • 4 = FATAL ERROR (a noticeable message in the middle of the screen)

result = krpano.resolveExpression(expression, caller*)
  • Resolve a krpano expression and return its result.
  • caller (optionally)
    • The 'caller' of the expression.
    • This is an Object that will be used as local variable scope.
    • This allows direct access to the attributes of that Object.

result = krpano.toBoolean(var)
result = krpano.BOOLEAN(var)
  • Convert any variable to a Boolean.
  • If the variable is null or undefined, false will be returned.
  • If the variable is already a Boolean, it will be returned as it is.
  • If the variable is a Number, +0, -0 and NaN will return false, all other values return true.
  • If the variable is a String, values like "true", "yes" or "on" (lowercase or uppercase, surrounding whitespace are ignored) will return true, all others will return false.
  • If the variable is an Object, true will be returned.

result = krpano.roundNumber(var, decimalplaces=0)
  • Round a Number to given decimal places.
  • The return value will be a String.
  • decimalplaces (optionally)
    • The number of decimal places, 0 by default.
    • Negative values work like positive ones, except that trailing zeros are automatically removed (except for a least one zero after the comma dot).
  • Examples:
    krpano.roundNumber(1.5) ⇒ "2.0"
    krpano.roundNumber(1.23, 6) ⇒ "1.230000"
    krpano.roundNumber(1.23, -6) ⇒ "1.23"
    krpano.roundNumber(1.0, -6) ⇒ "1.0"

result = krpano.clampNumber(value, min, max)
  • Clamp/limit a Number to be between the given min and max values.
  • min / max
    • The lower and upper limit for the result.
  • Returns the limited value.
  • Examples:
    val = krpano.clampNumber(val, 0.0, 1.0);
    val = krpano.clampNumber(val, -1.0, +1.0);
    val = krpano.clampNumber(val, -90.0, +90.0);

krpano.unload()

krpano.registerType(type, callback)
  • Register a custom type for Layers or Hotspots.
  • This can be used to create custom elements in krpano, e.g. to load custom file types. For example, this is used in the ThreeJS plugin to support loading 3D-Models as hotspots.
  • If a layer or hotspot has a custom, non-default type setting and there is a registerType() call with the same type, then the given callback function will be called when creating or destroying the element.
  • callback(object, url, okaycallback)
    • object - the layer or hotspot object
    • url - on creating the url if set, or the custom type name in angle-brackets if no url is used. On destroying null will be passed as url to allow a custom unload/destroy handling.
    • okaycallback - a callback to be called with true or false to signal if the creating is done and was successful. This will also trigger the onloaded event.
  • Example:
    <hotspot name="spot1" type="special" ... >
    and
    krpano.registerType("special", function(hotspot, url, callback)
    {
      if (url)
      {
        // create or load the special hotspot
        ... 
        // callback with true to signal that the creating was successful
        callback(true);
      }
      else
      {
        // destroy or unload the special hotspot
      }
    });

result = krpano.parsePath(path) or
result = krpano.parsepath(path)
  • Resolves the krpano placeholders in the given path string.
  • Return value: the resolved path string.

krpano.loadFile(rqurl, donecallback, errorcallback*)
  • Request to load a text-file as String.
  • donecallback and errorcallback - these functions will be called when the loading was successfully or has failed. The usage of the errorcallback is optionally.
  • Both callback functions will be called with an Object as parameter - and this Object has these attributes:
    • rqurl - the request url that was used on the loadFile call.
    • url - the parsed and resolved url of the file.
    • data - the loaded file content as String.
    • errmsg (errorcallback only)
      • A boolean flag with the default value true.
      • When kept set to true, krpano will show a default loading error message.
      • When set to false, no error message will be shown.

krpano.sendRequest(request, callback)
  • Send a HTTP server request.
  • request need to be an Object with the follow properties:
    • type - the request type: GET or POST
    • url - the server url.
    • data
      • The data to send with the request.
      • Can be an Object or a String.
      • Objects will be automatically converted to a JSON String.
    • headers (optionally)
      • Optional headers, can be an Object or a String.
      • String-syntax: "key:value, key:'a,b,c', ..."
    • cors (optionally) - when set to true, the CORS credentials will be added.
    • user and password (optionally) - HTTP Basic Authentication.
  • The callback function will be called with the given request Object as argument and adds these properties to it:
    • ok - true when the request was ok, false when it has failed.
    • statuscode - the HTTP status code, e.g. 404 on loading errors.
    • statustext - the HTTP status as text description.
    • responsetext - the response text.

krpano.mergeCallbacks(tasks, donecallback)
  • Merge the callbacks from multiple asynchronous tasks.
  • E.g. when multiple files are loaded and/or processed in parallel and another task should be executed when all previous ones are completed.
  • tasks - an Array that contains multiple functions.
    • Each function will be called with a callback function as argument.
    • This callback function must becalled when the function is completed.
    • Optionally, it is possible to pass an argument to this function as return/result value.
  • donecallback
    • This function will be called when all functions are completed.
    • The function gets an Array as argument that contains the all the return/result values from the called functions (in the same order the functions were defined).
  • Example:
    krpano.mergeCallbacks(
        [   function(callback){
                console.log("1 start");
                setTimeout(function(){  // randomly delay
                    console.log("1 done");
                    callback(1);        // here the function is done
                }, Math.random()*5000); 
            },
            function(callback){
                console.log("2 start");
                setTimeout(function(){  /// randomly delay
                    console.log("2 done");
                    callback(2);        // here the function is done
                }, Math.random()*5000); 
            },
            function(callback){
                console.log("3 start");
                setTimeout(function(){  /// randomly delay
                    console.log("3 done");
                    callback(3);        // here the function is done
                }, Math.random()*5000); 
            }
        ],
        function(results){
            // all functions from above are done
            console.log("all done, results:", results);  // "[1, 2, 3]"
        }
    );
    

krpano.customParsePath = function(url)
  • The customParsePath variable can be set to a custom Javascript function to do a custom filepath url parsing.
  • The function will get a filepath url that krpano will try to load as argument, and need to return the parsed and (optionally modified) filepath url.
  • All files loaded by krpano (except of the individual multiresoluion tiles) will get passed through that function.
  • Example:
    <action type="Javascript" autorun="preinit"><![CDATA[
      krpano.customParsePath = function(url)
      {
        console.log("url:",url);
        
        // load 'image2.jpg' instead of 'image1.jpg':
        if(url == "image1.jpg") url = "image2.jpg";
        
        return url;
      }
    ]]></action>	
    

krpano.customParseTilePath = function(url,cube,level,h,v,stereo,image)
  • The customParsePath variable can be set to a custom Javascript function to do a custom filepath url parsing for multiresoluion tiles.
  • The function will get a filepath url that krpano will try to load as argument, and need to return the parsed and (optionally modified) filepath url.
  • After that function the default krpano tile-url parsing will be done.
  • Parameters:
    • url - the base tile-url template.
    • cube - the cube side index, range 0-5, an index into the cubelabels values. Non-cubical panos will use the value 1 here.
    • level - the level index, range baseindex to N.
    • h, v - horizontal and vertical tile index, range baseindex to N.
    • stereo - stereo side, 0 or 1, an index into the stereolabels values.
    • image - the related xml <image> element as object.
  • Example: Custom Tile-URLs

result = krpano.screentosphere(x,y)
result = krpano.spheretoscreen(h,v)
  • Functions for converting between screen and spherical coordinates.
  • Return value: an Object with x and y properties. The values of these properties can be NaN (Not a Number) if the conversion wasn't possible.

result = krpano.spheretospace(h,v,depth)
result = krpano.spacetosphere(x,y,z)
  • Functions for converting between spherical and XYZ 3D space coordinates
  • Return value:
    • spheretospace - an Object with x,y,z properties.
    • spacetosphere - an Object with h,v,depth properties.

krpano.events.addListener(eventname, callback, once)
krpano.events.removeListener(eventname, callback)
Add or remove Javascript listeners / callback-functions for any krpano events.

Parameters:
  • eventname
    • The name of any krpano event, e.g. "onclick" for the onclick event.
    • It is possible to assign several events at once to the same callback by separating the names by | or , characters.
    • It is possible to put the once parameter optionally directly into this list instead of using an additional parameter, e.g. "onclick,once".
  • callback
    • The Javascript function to be called on the given event.
    • Some events, like mouse or keyboard events, will provide an Event object as parameter.
    • Special case: when calling events.removeListener() with the String * as callback, then all assigned callbacks will be removed.
  • once (optionally)
    • When set to "once", the callback function will be called only once and then automatically be removed.
krpano.events.dispatch(eventname, instantly*)
Dispatches / calls the given event listeners from all <events> elements.

Parameters:
  • eventname
    • The name of the krpano event.
    • Can be also any custom name, when event listeners for that name are used.
  • instantly (optionally)
    • A Boolean setting (true or false, false by default).
    • When set to true, the events will be called and executed instantly, when not set or set to false, the events will be called after the current actions calls.
2 Parameters - krpano variable path:
krpano.addChangeListener(varpath, callback)
krpano.removeChangeListener(varpath, callback)
3 Parameters - direct Object access:
krpano.addChangeListener(object, key, callback)
krpano.removeChangeListener(object, key, callback)
Make a callback when an Object key/property changes.
  • This will convert the given Object property to a setter/getter function and call the callback function on each change/set.
  • The key/property can be even already a setter/getter and keeps working.
  • When the key/property doesn't exists yet, it will be created with the value undefined.

Parameters:
  • varpath
    • The name / path of any krpano variable, e.g. "view.hlookat".
  • object
    • Any Javascript-Object.
  • key
    • The name of the key/property/variable of the Object.
  • callback
    • The Javascript function to be called on the given event.
    • Some events, like mouse or keyboard events, will provide an Event object as parameter.
Examples
Either:
krpano.addChangeListener("view.hlookat", function(){...});
or:
krpano.addChangeListener(krpano.view, "hlookat", function(){...});

Legacy / Compatibility Interface

This was the first external krpano Interface (already since the Flashplayer-times) and it allowed connecting and interacting between two technically different systems. With it the Flashplayer-based and the HTML5-based krpano viewer could be controlled by Javascript using the same API.

This set/get/call called interface consists of these three basic functions: This simple interface allows controlling all kinds of krpano, but compared to direct Javascript access it is slower (due to the additional parsing steps) and may make the Javascript code look less nice. Since the Flashplayer is no longer a thing anymore, it is perfectly fine to use direct Javascript access now.

A quick example using set/get/call:
krpano.call("addhotspot(test);"); krpano.set("hotspot[test].url", "image.png"); krpano.set("hotspot[test].ath", krpano.get("view.hlookat") ); krpano.set("hotspot[test].atv", krpano.get("view.vlookat") );
and the same with direct Javascript usage:
var hs = krpano.actions.addhotspot("test"); hs.url = "image.png"; hs.ath = krpano.view.hlookat; hs.atv = krpano.view.vlookat;
Both examples are doing the same, but the direct Javascript one would be much faster. For such short example code the performance wouldn't matter, but when doing hundreds of such operations every frame, then the difference can become very noticeable.

A note for older krpano versions:

In older krpano versions (before 1.20) it was additionally necessary to call:
krpano = krpano.get("global");
to get direct access to the krpano. That global object is the root-level object of the whole krpano API structure and from there all variables, objects and functions are directly accessible. Without that call, only the set/get/call interface would be available.

krpano Plugin Interface

The krpano Plugin Interface is a small and simple interface for developing own plugins. A plugin can be either a 'code-only' plugin that extends krpano with additional functionality or controls krpano and / or it can be a 'graphical-plugin' which shows or does something on the screen.
Here an example plugin code with the basic structure for a krpano Javascript plugin:
At first there need to be a globally defined Function object named krpanoplugin. All further code need to be inside that function, everything outside of it will get stripped!

This krpanoplugin Function object can have these public functions:
  • A registerplugin function - this function will be called from krpano when the plugin will be loaded. The function provides a krpano Interface Object and a krpano Plugin Object.
  • An unloadplugin function - when the plugin will be removed from krpano, then this function will be called. Here all elements and events that the plugin has added should be removed.
  • And optionally an onresize function to allow the plugin reacting on size changes of the plugin element.
The plugin itself can add custom functions or attributes to krpano just by adding / setting them directly to the krpano object or to the plugin object. For custom attributes that can be set from the xml there is additionally the registerattribute function - it allows adding an attribute with a default value while keeping the value from the xml. And the registerattribute function can be used to add setter/getter attributes - this are attributes which will cause automatically calling a get or set function when accessing the variable - this can be used to get notified when an attribute will been changed.
Functions of the 'krpanoplugin' Function object:

krpanoplugin.registerplugin(krpanointerface, pluginpath, plugin)
  • The registerplugin() function will be called when the plugin was loaded into krpano and is ready for usage.
  • Here the plugin can add / register attributes, functions, add graphical content to the plugin or to the viewer and do many things more.
  • Parameters that will be passed with the registerplugin() function:
    • krpanointerface
      The krpano Interface Object - this object provides access to interfacing functions and to the whole krpano data structure.
    • pluginpath
      A String with the 'full path' to the plugin object, e.g. "plugin[name]".
    • plugin
      The krpano Plugin Object - this object provides direct access to all plugin attributes and functions.

krpanoplugin.unloadplugin()
  • The unloadplugin() function will be called from krpano when plugin will be removed.
  • Here the plugin should remove all content that it has added (e.g. graphical objects, event listeners, timers, ...).

krpanoplugin.onresize(width, height) (optionally)
  • The onresize() function will be called when the plugin will be resized.
  • The parameters width and height are the new size in pixels.
  • Here the plugin can adjust or resize its own graphical content.

krpano Plugin Object

The 'plugin' object it the internal representation of the xml <plugin>, <layer> or <hotspot> elements. All attriutes and actions of the element are directly accessible by it.
Special plugin-related attributes of the 'plugin' object:

plugin.sprite
  • The HTML <div> element of the plugin object.
    Note - when using the plugin as hotspot, then the sprite object is only available when rendering the hotspot as CSS-3D-transformed HTML element (see the renderer setting)!
  • The sprite object can be used for adding custom display elements (HTML DOM elements) to the plugin itself.

plugin.videoDOM 
  • A special attribute to allow the plugin providing a HTML5 video object for rendering.
  • The krpano viewer will use that video object for rendering when using the plugin as hotspots or as pano image (via url="plugin:video").
  • Setup: videowidth and videoheight attributes with the size of the video need to be added to plugin object, and once the video is ready for rendering the onvideoreadyCB function of the plugin be called. For all details please see the example source code of the videoplayer plugin.
  • Special usage: with some tricks it's also possible to use a HTML5 canvas object as video source. Use the canvas as videoDOM and add these 'faked' properties to it: readyState=4, videoWidth=canvas.width, currentTime=time or frame number (should change when the content changes). Example
Special plugin-related functions of the 'plugin' object:

plugin.registercontentsize(width, height)
  • Define the 'default' size of the plugin display content.
  • This is the size that will be used if the user hasn't set width or height.

plugin.assignEvents(htmlelement, mode)
  • Assign the krpano plugin events to the given HTML element.
  • mode - "add" for adding the events, "remove" for removing.
  • This can be used for special custom added HTML elements, e.g. svg path elements.

krpano Base Objects

All krpano objects and elements and all xml-nodes (mapped to objects and arrays) and also the krpano Interface Object are derived from a krpano Base object. The Base object has some basic functions for adding / registering new attributes and for creating sub-structures.
Functions of Base objects:

object.registerattribute(attributename, default, setter, getter)
object.registerattribute(attributename, default, setter)
object.registerattribute(attributename, default)
  • Adds a new attribute to the object and sets it to the given default value. If the object already has that attribute (e.g. from the xml) then the current value will be kept but the type of the attribute will be converted to the type of the given default value. That automatic type conversion will work for 'Number' and 'Boolean' datatypes.
    For example: If the attribute was set in the xml file to "123", then the type of the attribute is a 'String', but when registering that attribute with a 'Number' default value, then the attribute will be also converted to 'Number' with the Value 123.
  • Setter / Getter (optionally)
    Optionally it's possible to use setter and getter functions instead of a normal attribute.
    There are two options here:
    1. Using setter AND getter functions - in this case when the attribute will be set to a new value, the setter function with that new value will be called, and when the value of the attribute will be read then the getter function will be called to return the value. Note - in this case the setter/getter functions will need to store the actual value by itself anywhere!
    2. Using ONLY a setter function - in this case the current value of the attribute will be stored internally and the setter function will be called on changes with:
      setter(newvalue, oldvalue, object, attributename)
      This allows using fewer code for simple cases and/or sharing the same setter function for multiple attributes. The setter function can optionally also return a modified new value.

object.removeattribute(attributename)
  • Removes an attribute from the current object.

object.getattributes()
  • Get all current attributes of the object.
  • Returns a Javascript Array with the names of all attributes.

object.setattributes(object,object2*,object3*,...)
object.setvars(object,object2*,object3*,...) (short form)
  • Copy all attributes from the given Javascript object to the krpano object.
  • Can be used to set several attributes/variables at once.
  • Example usage:
    var layer = krpano.addlayer();
    layer.setvars({type:"text", text:"test", align:"center"});

object.createobject(objectname)
  • Create a new krpano Base Object inside / under the current object.
  • Returns the new created krpano Base Object.
  • If the object already exists then the exiting object will be kept and returned.

object.removeobject(objectname)
  • Removes an object from the current object.

object.createarray(arrayname)
  • Create a new krpano Array inside the current object.
  • Returns the new created krpano Array Object.
  • If the array exists already, then the current Array will be kept and the existing Array will be returned.

object.removearray(arrayname)
  • Removes and destroys a krpano Array object.

krpano Array and Array-Items

Arrays in krpano are special objects, not normal Javascript Arrays. A krpano Array allows to access the items the same time by name and by index. A krpano Array will be automatically created when a node in the xml has a 'name' attribute or when a variable with a 'array path' like 'arrayname[itenname].variable' will be set/created.

The items of the arrays are derived from krpano Base Objects and have additional attributes for name and index. Beside of that, these objects can store any kind of attributes or functions, also additional krpano Arrays and Objects.
Attributes of the krpano Array Objects:

array.count
  • The number of elements in the array.
  • Can be changed dynamically, but only decreasing makes sense, e.g. set it to 0 to remove all items.
Functions of the krpano Array Objects:

array.createItem(name or index) or
array.createarrayitem(name or index) (callable from xml)
  • Create a new item inside the array.
  • If using 'auto' or null/undefined as name, an automatic unique name will be generated.
  • If using a name and not an index, the new item will be added at the end of the array.
  • Returns the new created array item object.
  • If there exists already an item with that name or index, then no new item will be created, instead the existing item will be returned.

array.insertItem(name, index) or
array.insertarrayitem(name, index) (callable from xml)
  • Create a new item and insert it at the given index.
  • If using 'auto' as name, an automatic unique name will be generated.
  • Returns the new created array item object.
  • If there exists already an item with that name, then no new item will be created, instead the existing item will be moved to the given index.

array.getItem(name or index)
  • Get an existing array item.
  • Returns the array item object or null if the items doesn't exist.

array.renameItem(oldname, newname) or
array.renamearrayitem(oldname, newname) (callable from xml)
  • Changes the name of an existing item.

array.removeItem(name or index) or
array.removearrayitem(name or index) (callable from xml)
  • Removes an item from the array.
  • The removeItem() function returns the removed item object.
  • The removearrayitem() function is the same like the removeItem() function but without return value and also callable from XML / krpano Actions.

array.addChangeListener(callback)
array.removeChangeListener(callback)
  • Make a callback when the array gets changed, that means when items were added, removed, renamed or sorted.
  • The callback function gets the current array as first argument:
    function callback(array){ ... }

array.getArray()
  • Get the internal Javascript Array.
  • Can be used for direct fast access.
  • The Array item attributes can be changed, but the Array itself (length, order, adding or removing) NOT! Otherwise the name/index mapping would be invalid.

array.forEach( callback )
  • Javascript Array.forEach
  • The Javascript callback function will be called for each Array item with the following arguments:
    callback(item, index)

Default Attributes of the krpano 'Array-Item' Objects:

arrayitem.name
  • The name of the current array item (read-only).
  • This name can be used for direct access to the array item.

arrayitem.index
  • The 0-based index of the current array item (read-only).

krpano WebGL API

The krpano viewer exposes a WebGL API for getting access to the internal WebGL canvas and context. The WebGL API allows creating custom post-processing shaders and rendering custom elements.
krpano.webGL
  • The krpano WebGL API object.
  • If the object is null, then there is no WebGL support.

krpano.webGL.canvas
  • The internal krpano WebGL <canvas> element.

krpano.webGL.context

krpano.webGL.projectionMatrix
  • The current krpano projection matrix.
  • A 4x4 Matrix as a linear Float32Array with 16 elements.

krpano.webGL.depthbufferbits
  • The bit-depth of the rendering depthbuffer.
  • Typically 24bit, but in some cases (some browsers or when rendering to a framebuffer, e.g. during post-processing) is can be also only 16bit.
  • When only 16bit are available this can cause to a reduced depth-accuracy (when using depthmaps/3D-models).
  • This variable can constantly change depending on the current rendering state (e.g. when rendering to the screen or to the framebuffer).

krpano.webGL.addListener(eventname, callback)
krpano.webGL.removeListener(eventname, callback)
  • Add or remove special rendering event listeners.
  • eventname="renderframe"
    • This event will be called after rendering the pano image and after the post-processing phase 1, but before rendering the krpano hotspots. It can be used to render custom elements.
    • callback(framebuffer, viewport, pano, panoview, stereo)
      • framebuffer - the current krpano WebGL rendering framebuffer (can be null when currently rendering to the screen backbuffer). This can be used normally with a gl.bindFramebuffer() call or with the krpano redirectBackbuffer() function when there is no control about the current framebuffer binding.
      • viewport - the current viewport as Array with 4 values: [x,y,width,height]
      • pano - an Object with information about the current pano:
        • Can be used to render something only for a specifc pano image/scene, e.g. when rendering two panos the same time during blending.
        • id - a consecutive number of used pano images.
        • image - the related <image> Object.
        • suspended - when set to true, then this is an 'old' pano that is only rendered during blending.
      • panoview - an Object with information about the current pano-view:
        • h, v, r ⇒ view.hlookat, view.vlookat, view.camroll
        • tx, ty, tz ⇒ view.tx, view.ty, view.tz
          (adjusted with stereo-offsets when stereo-rendering)
        • rx, ry ⇒ view.rx, view.ry
      • stereo - the stereo rendering state: 0=off, 1=left, 2=right
  • eventname="hittest"
    • This event will be called to check hits / collisions with a custom elements.
    • When the hit is on a custom type hotspot, krpano can automatically handle the hotspot events (like onover/onout, onclick and so on).
    • callback(eventtype, origin, direction, hitresult, hittesthotspots)
      • eventtype
        • null - no user action, just checking for a hit (e.g. on hovering)
        • raycast - checking for a 3D collision, occlusion
          • The 3D geometry that is used for collision testing, should be checked here.
          • When using hotspots for the 3D geometry, only the hotspots in the hittesthotspots Array should be checked in this case.
        • ondown - mouse-down or touch-down
        • onup - mouse-up or touch-up
        • onclick - mouse-click or touch-down/up event
        • onwheel - mouse-wheel event
        • ongesture - gesture event
      • origin - the origin of the hit-test ray as 3D point object {x,y,z}.
      • direction - the direction of the hit-test ray as 3D point object {x,y,z}.
      • hitresult - an Object with information about the hit-result:
        • d - distance from the origin to the hit-point, -1 if there was no hit yet
        • x,y,z - the hit-point 3D position
        • nx,ny,nz - the normal vector of the surface at the hit-point
        • hs - hotspot object (if the hit was on a hotspot)
        • Note: the hitresult object can be already filled with hits on a krpano 3D-model or krpano hotspots, therefore check if the new hit-distance is shorter then the current stored one before filling the hitresult object with new information about the hit.
      • hittesthotspots - an Array of all krpano hotspots with hittest=true.
      • return value - true if there was a hit, false if not

krpano.webGL.createPostProcessingShader(source, uniforms, name, onrendercallback)
  • Create a krpano post-processing shader (a WebGL GLSL fragment shader).
  • Parameters:
    • source
      • A GLSL fragment shader source code as string.
      • The shaders code needs to have:
        • A sm named sampler2D - this will be the current screen as input texture.
        • A tx named vec2 varying - this will be the current texture coordinate.
        • Optionally a sz vec2 uniform - this will contain the screen size.
    • uniforms
      • A comma separated list of the uniform names used in the shader.
      • The 'uniform location' will be automatically stored at the returned shader object with the same name.
    • name (optionally)
      • A name for the shader.
    • onrendercallback (optionally)
      • A Javascript callback function that will be called before rendering the shader.
      • That could be used to set or update uniform values.
      • Function parameters:
        function onrendercallback(side, shader, gl)
        • side - the stereo side, 0=non-stereo, 1=left, 2=right
        • shader - the current shader object
        • gl - the current WebGL context
  • Return:

krpano.webGL.ppShaderArray
  • An array of post-processing shaders.
  • Here custom shaders can be added, inserted or removed.
  • The shaders will be processed by the order in that array.
  • These shaders will be executed after the COMPLETE rendering of a frame. That means it will affect everything that was drawn before by WebGL - the pano and also the hotspots.

krpano.webGL.ppShaderArray2
  • An array of post-processing shaders.
  • Here custom shaders can be added, inserted or removed.
  • The shaders will be processed by the order in that array.
  • These shaders will be executed AFTER the pano rendering, but BEFORE the hotspots-rendering. That means it will affect only the pano, but not the hotspots, they will be drawn on top of the processed image.

krpano.webGL.useShader(shader)
  • Select/activate the shader for interfacing, e.g. for setting uniform values.

krpano.webGL.deleteShader(shader)
  • Delete the shader (free-up the WebGL resources).

krpano.webGL.restoreProgram()
  • Notify krpano that it need to restore the krpano WebGL program on the next usage.
  • This need to be called when external WebGL code had changed the current WebGL program.

krpano.webGL.resetState()
  • Restore several WebGL state settings back to the ones krpano uses.
  • This need to be called when external WebGL code had changed the current WebGL states.
  • This function automatically also calls the restoreProgram() function.

krpano.webGL.redirectBackbuffer(enable, framebuffer, stereo)
  • Intercept the WebGL context calls to ensure that the rendering will be done into the specified framebuffer and not the screen's backbuffer.
  • This can be used to combine the output from external renders with the rendering from krpano, even when there is no control over the current framebuffer state.
  • As long as enabled, all following gl.bindFramebuffer() calls with null as target (which means rendering to the screen backbuffer), will bind the actual framebuffer to the given one instead.
  • Parameters:
    • enable - true to enable, false to disable the redirection
    • framebuffer - a WebGL framebuffer
    • stereo - the stereo rendering state: 0=off, 1=left, 2=right

krpano.webGL.makeScreenshot(width, height, hotspots, type, jpegquality, crop, sizeinfo, cache)
  • Make a screenshot in the given size and given type.
  • Parameters:
    • width, height - The size in pixels. If set to 0, the current size will be used.
      If the size will be larger than actually possible, then the size will be automatically proportionally downscaled.
    • hotspots - Render also the (webgl) hotspots: true or false (false by default).
    • type - This setting defines what will be returned by the function:
      • "jpeg" - A JPEG image as data-url / base64 encoded string. (default)
      • "png" - A PNG image as data-url / base64 encoded string.
      • "raw" - The direct pixels as Uint8Array with RGBA bytes per pixel.
      • "canvas" - A 2D Canvas Object with the screenshot image.
    • jpegquality - The JPEG image / compression quality, from 0.0 (worst) to 1.0 (best) and 0.85 by default. Only used for type="jpeg" and ignored for all other types.
    • crop - An optional Object with {x,y,w,h} properties to define an optional cropping of the screenshot image.
    • sizeinfo - An optional Object with {w,h} properties to pass to get information about the pixel size of the resulting image (useful for raw and image types).
    • cache - An optional empty Object where krpano can store internal buffers. When doing several screenshots with the same size, this can makeScreenshot calls faster. That object should be stored somewhere on application side and passed to all makeScreenshot calls.
  • If there will be an error, null will be returned.
  • Usage notes: Even if this function is called 'screenshot', it technically renders a whole new frame directly in the given size/resolution (no interpolation).
    This also allows changing all kind of settings (e.g. a different viewing direction) before doing the 'screenshot' (and then restoring them after it) to render something different to that what's currently shown on the screen.
    There is only one limitation here - only the currently loaded pano tiles/image are used. That means if trying to render a completely different view (e.g. into other direction or using other zoom-level) when using a multires pano, then there might be only the preview image available there to render.

Javascript Polyfills

The krpano viewer automatically installs Polyfills for these Javascript Functions if they are not available in the Browser:

Examples

Source: js-api-examples.html
Several examples for using the Javascript API of the krpano viewer:
  • How to use krpano directly from and with Javascript.
  • How to load xml files or xml strings.
  • How to load image directly without any xml involved.
  • How to load 3D-models and navigate in them.
  • How to change the view.
  • How to add and edit hotspots.
  • How to add plugins.