NAV
javascript

Introduction

Zwibbler is a full-featured javascript library that provides drop-in vector-graphics editing for your HTML5 application. This document describes how to get up and running with Zwibbler quickly, and includes full details on how to configure it for your purpose.

Use the Configuration Playground to experiment with different settings.

Features

Quick Start

To get started with Zwibbler

  1. Include the Zwibbler script on an HTML page
  2. Create a <div> element and position it to contain the Zwibbler application.
  3. Call the Zwibbler.create() function, specifying the DOM element of the DIV container, and configuration settings.
  4. Use the returned Zwibbler Context to control Zwibbler from javascript, or to open and save documents.

Integrating Zwibbler

var context = Zwibbler.create("myelement", {});

Zwibbler can be integrated using code like this:

The Zwibbler.create() function takes the ID of the DIV element in which to place Zwibbler, and the configuration options. It returns the ZwibblerContext.

Example

<!DOCTYPE html>
<html>
<body>
    <div id="zwibbler" style="margin-left:auto;margin-right:auto;border:2px solid red;width:800px;height:600px;"></div>
    <input type="button" onclick="onSave()" value="Save"/>
    <input id="loadButton" type="button" onclick="onLoad()" disabled="disabled" value="Load"/>
    <input type="button" onclick="onImage()" value="Open as image"/>
    <input type="button" onclick="zwibbler.onResize()" value="Open as image"/>
    <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
    <script src="zwibbler2.js"></script>
    <script type="text/javascript">
        var zwibbler = Zwibbler.create("zwibbler", {
            showPropertyPanel: true
        });

        var saved = null;
        function onSave() {
            saved = zwibbler.save("zwibbler3");
            $("#loadButton").removeAttr("disabled");
        }

        function onLoad() {
            zwibbler.load("zwibbler3", saved);
        }

        function onImage() {
            var dataUrl = zwibbler.save("png");
            window.open(dataUrl, "other");
        }
    </script>
</body>
</html>

How it looks

Here is how Zwibbler looks with a minimal configuration:

var ctx = Zwibbler.create("mydiv", {
    showToolbar: true,
    showColourPanel: true
});

Zwibbler with minimal configuration

Various parts of the user interface can be turned off. Here is how it looks with a few more things turned on, and labelled:

var ctx = Zwibbler.create("mydiv", {
    showToolbar: true,
    showColourPanel: true,
    showPropertyPanel: true,
    debug: true
});

Zwibbler with all parts labelled

Guide to Common Scenarios

Updating the User interface

var zwibbler = Zwibbler.create("MyZwibblerDiv", {});
   zwibbler.on("document-changed", function() {
        var canUndo = zwibbler.canUndo();
        var canRedo = zwibbler.canRedo();
        var dirty = zwibbler.dirty();

        // enable/disable the undo/redo buttons

        // if the document is dirty, enable the save button.
   });

Whenever the document changes for any reason, Zwibbler emits the event document-changed. This event is emitted whether the document is changed as a result of a user action, or if you changed it programmatically. Handle this event, and you can do things such as disable or enable buttons for saving or undo / redo.

Manipulating the Undo Stack

Certain API functions add to the undo stack when you call them, so the user will be able to undo them. By default, each time you call such a function, one undo item is created. Sometimes, you might not want the user to be able to undo the action. For example, if you create a document template with some pre-existing items. Other times, you might want multiple actions to be undone at once. For example, creating a rectangle, rotating it, and moving it to a specific location.

You can do these things using a transaction. To begin a transaction, call beginTransaction. You can then manipulate the document using the Javascript API, using functions such as createNode, translateNode, or addPage. After calling beginTransaction, you must call abortTransaction, commitTransaction, or commitIrreversibleTransaction to allow future editing. If you begin a transaction and you are already in one, Zwibbler keeps track of the number of nested calls and does nothing until you call a commit function an equal number of times.

Functions in the Undo Stack :

Using Multiple Pages

You can use multiple pages or set a paper size. Zwibbler supports one paper size for the whole document. You can choose to use a paper size of “none” to allow infinite paper area. Otherwise, set the paper size using a configuration option or by the API after zwibbler has been created.

Another important consideration is zooming. Use the setZoom function to set a zoom. When passed a number, the document will be scaled. However, if you use the special values “width” or “page” then the document will always be scaled so that the page width or full page fits into the viewing area.

The Zwibbler API provides all of the functions needed to create your own page selector. The draw function allows you to create previews of each page. For your convenience, there is a built-in page selector that you can enable with the showPageSelector configuration option.

These configuration settings relate to pages.

Functions related to Pages :

Adding Buttons

Zwibbler.addButton({
    // The name of the button, for debugging purposes.
    name: "kitty",

    // The image to show on the toolbar. This should be 50 pixels in width.
    // The URL will be used as-is, and the imageFolder configuration setting
    // will not be used for this image.
    image: "kitty.png",

    // The function to be called when the button is clicked. The parameter is
    // the ZwibblerContext that will allow you to manipulate the drawing.
    onclick: function(ctx) {
        // In this example, when the button is clicked we insert an image into
        // the document. The image will not be resizable by the user.
        ctx.createNode("ImageNode", {
            url: "kitten.png",
            lockSize: true
        });
    }
});

Most users choose to create their own toolbars. If you have your own toolbar images, arrange them on the page, and call the appropriate zwibbler.useXTool() function when one is clicked.

To get you up and running quickly, Zwibbler includes a built-in toolbar. You can extend Zwibbler by adding buttons to this built-in toolbar. When the button is clicked, your function will be called.

Protecting parts of documents with Layers

You can make certain parts of documents immobile using layers. For example, you might have a “teacher” and a “student” layer. While marking, the teacher will not be able to change what the student has drawn, and vice versa.

Functions related to Layers :

The visibility of layers and the active layer is not saved with the document, so if you use these features, you will have to set them each time a document is opened or when a new document is created. When a document is opened, the active layer is set to “default”.

Creating a custom tool

function MyCustomTool(zwibblerContext) {
    // initialize any variables here here.
    this.ctx = zwibblerContext;
}

MyCustomTool.prototype = {
    leave: function() {
        // Called by Zwibbler when a different tool is selected
        // for any reason. Clean up here.
    },

    onMouseClick: function(x, y, e) {
        // The x, y coordinates are coordinates in the document, taking into 
        // account zooming and scrolling. "e" is the DOM event that caused the 
        // mouse click.
    },

    onDoubleClick: function(x, y, e) {

    },

    onMouseDown: function(x, y, e) {

    },

    onMouseUp: function(x, y, e) {

    },

    onMouseMove: function(x, y, e) {

    },

    onMouseWheel: function(x, y, change, e) {
        // The mouse wheel event.
    },

    onTouch: function(x, y, e) {
        // Use e.type to distinguish touchstart, touchend, and touchmove events.

        // return false, and Zwibbler will automatically call the appropriate onMouse() functions instead.
        return false;
    },

    onColour: function(colourName) {
        // Called when the user selects a new colour
    },

    onOpacity: function(opacity) {
        // Called when the user selects a different opacity.
    },

    onRedraw: function(canvasCtx) {
        // called after the canvas is drawn, with the HTML canvasContext
        // scaled and translated.
    }
};

// To activate the tool
ctx.useCustomTool(new MyCustomTool(ctx));

Zwibbler interprets mouse and touch events differently depending on which tool is selected. For example, when you move the mouse in the brush tool, a line is drawn, but with the pick tool, a selection box is drawn instead. You can create your own custom tool and use it by calling useCustomTool. To create a custom tool, make an object and implement the functions that you need. All of the functions are optional.

Example of a Custom Text Stamp Tool

function TextStampTool(zwibblerContext, text, fontName, fontSize, doneFn) {
    // initialize any variables here here.
    this.ctx = zwibblerContext;
    this.text = text;
    this.fontName = fontName;
    this.fontSize = fontSize;
    this.doneFn = doneFn || function(nodeid) {};
}

TextStampTool.prototype = {
    enter: function() {
        this.ctx.setCursor("none");
    },

    leave: function() {
        // Called by Zwibbler when a different tool is selected
        // for any reason. Clean up here.
        this.ctx.setCursor("pointer");
        this.ctx.redraw();
    },

    onMouseClick: function(x, y, e) {
        // The x, y coordinates are coordinates in the document, taking into 
        // account zooming and scrolling. "e" is the DOM event that caused the 
        // mouse click.
        this.ctx.beginTransaction();
        var node = this.ctx.createNode("TextNode", {
            fontName: this.fontName,
            fontSize: this.fontSize,
            text: this.text,
            scaleFont: false
        });
        this.ctx.translateNode(node, x, y);
        this.ctx.commitTransaction();
        this.ctx.usePickTool();
        this.doneFn(node);
    },

    onMouseMove: function(x, y, e) {
        var self = this;
        this.ctx.redraw(function(canvas) {
            canvas.fillStyle = "rgba(0,0,0,0.5)"; // 50% black
            canvas.font = self.fontSize + "px \"" + self.fontName + "\"";
            y += self.fontSize;
            canvas.fillText(self.text, x, y);
        });
    }
};

This tool will allow the user to stamp text down on the drawing.

Including DOM elements in the drawing

A common scenario is including math equations in the drawing using MathML. The browser can render such nodes to HTML, but Zwibbler cannot. The solution is to include DOM elements in the drawing.

Zwibbler manages the placement of these HTML elements in the drawing, so the user can move them around and scale them like other shapes.

Step 1: Create a Zwibbler node for the HTML element in the drawing

Example: Include a YouTube video in a drawing

ctx.createNode("DomNode", {
   // ID of YouTube video
    data: "Kdgt1ZHkvnM"
});

Use the createNode function to create a special Zwibbler node of type DomNode. You can set its data property to something that will allow you to later create the appropriate HTML element.

Step 2: Handle the convert-dom-request event

ctx.on("convert-dom-request", function(id, dataString) {
    // Given the data, create a DOM element and call 
    // ctx.setDomElement for the node.        

    var iframe = document.createElement("iframe");
    iframe.setAttribute("class", "my_video_class");
    iframe.setAttribute("width", "300");
    iframe.setAttribute("height", "169");
    iframe.setAttribute("src", "http://www.youtube.com/embed/" +
        dataString + "?rel=0");
    iframe.setAttribute("frameborder", "0");
    ctx.setDomElement(id, iframe);
});

Zwibbler may need to recreate the HTML element from its data when a document is loaded, or when the user deletes and then later undoes the deletion of the element. When this occurs, it sends the convert-dom-request event. Handle this event by creating an HTML element from the Zwibbler node’s data and using the setDomNode function to give it to Zwibbler.

Associating Data with Drawing

For your use, every node in the drawing has a “tag” that can be set using ctx.setNodeProperty(). You may set this to a unique identifier that you can use to associated data with the node, or use it to easily find nodes of a certain type.

Function related to Nodes :

Spot Highlight

ctx.useCircleTool({
    spotHighlight: true
});

When one or more PathNodes with the spotHighlight property exists, the entire drawing is darkened except for the area inside shapes.

Enable this property when activating the tool.

Configuration settings related to Spot Highlight :

Eraser

// METHOD 1: ------------------------------------------------------------
// When the "selection tool" is clicked
ctx.usePickTool();

// When the "delete" button is clicked
ctx.deleteNodes(ctx.getSelectedNodes());




// METHOD 2: ------------------------------------------------------------
ctx.useBrushTool({
    lineWidth: 10,
    strokeStyle: "erase",

    // optional: prevents the user from being able to move the erase stroke.
    layer: "my_eraser_layer"
});

Zwibbler is a vector graphics program. The user can always pick up items and move them. This presents challenges for erasing things the way people are used to. There are two methods to implement an eraser.

Method 1: Delete selection

The user clicks a button to go into selection mode. Then he or she may select the objects to delete. Upon clicking the delete button or pressing the delete key on the keyboard, the objects are deleted.

Method 2: Eraser tool

The user can use a special eraser brush. This brush paints in the same colour as the background, whether it is clear or a background image. Although it is intuitive to use, the user can still move objects from under the erased portions, or select the erased brush stroke itself.

See also: useBrushTool function

Node Properties

Shapes and objects in a Zwibbler document are called Nodes. There are several major types of nodes, and they each have properties that describe the way they look.

// Create an image url
var node = ctx.createNode("ImageNode", {
    url: "http://zwibbler.com/logo.png"
});

// Later change its image
ctx.setNodeProperty(node, "url", "http://zwibbler.com/logo-white.png");

You can create a node using the createNode function or update the properties of an existing node using the setNodeProperty function.

Types of nodes

Type Description
ImageNode An image.
PathNode An open or closed shape. A PathNode may also contain text if it is a closed shape.
BrushNode A sequence of coordinates representing a brush stroke.
TextNode Text
DomNode Represents an HTML element included in the drawing. See Including DOM elements in the drawing
GroupNode A group is a group of nodes. Whenever one is selected, all the others in the group are selected as well. You cannot create a group node directly. Instead, use the createGroup function

Properties of nodes

Property Description
arrowSize (PathNode) If non-zero, it is the size of the arrow head(s). The corresponding values shown in the user-visible property panel are: None=0.0, Tiny=10.0, Small=15.0, Medium=20.0, Large=30.0
arrowStyle Use simple for an open arrow head or solid for a closed arrowhead.
arrowXOffset (PathNode) This specifies how far down the arrow ends reach, along its trunk, from the end of the line. When set to 0, there will be no descent, so the arrow will take the shape of a T. When set to the default of null, the arrowSize is used for this value, so the arrow’s sides will be at a 45 degree angle from the line.
background (TextNode) A colour for the background of the text box.
border (TextNode) A width and colour for the border of the text box. Example: “1px red”
cloudRadius (PathNode) When set to a value greater than 0, the path is drawn as a cloud shape using overlapping semicircles of the given radius.
commands (PathNode) an array of path commands, before the transformation is applied, that define a PathNode. Each command consists of 1 to 7 numbers. They are described below.
dashes (PathNode) A string. If non-empty, it is a comma-separated list of numbers, for example, “5,2”. This means draw the line in dashes, five pixels on, then skip two pixels, and so forth. The corresponding values shown in the user-visible property panel are: Solid=“”, Short dashes=“5,5”, Long dashes=“10,5”.
doubleArrow (PathNode) Use true for an arrowhead on both ends.
fillStyle The HTML or CSS colour code of the inside of a shape.
fontName The name of the font.
fontSize The size of the font, in pixels.
layer The name of the layer on which the shape is created. This is, by default, “default”
lineWidth The thickness in pixels of the line. The corresponding values in the user-visible property panel are: Pencil=1.0, Pen=2.0, Marker=4.0, Brush=10.0.
lockAspectRatio If set to true, the user will be able to make this shape larger or smaller, but will not be able to stretch it horizontally or vertically.
lockEditMode Every shape may have an “edit mode” engaged if the user clicks on it after it is already selected. If set to true, the user will not be able to slow-click and edit the points, or crop the image if applicable.
lockPosition If set to true, the user will not be able to move this node.
lockRotation If set to true, the user will not be able to rotate this node.
lockSize If set to true, the user will not be able to resize this node.
matrix The transformation matrix of the node. At this time, you cannot set this directly. Use the translateNode function and scaleNode function to update it.
roundRadius (PathNode) The radius by which the corners or bends of the line are rounded. This is different from path smoothness because the rest of the line is drawn straight and only the corners are rounded.
rotationHandles This is an array of groups of four numbers, [x1, y1, y1, y2, …]. x1, y1 define the location of the rotation handle, and x2, y2 define where this handle rotates around. There may be multiple rotation handles specified. The coordinates are in the node’s coordinate space, so they are affected by its transformation matrix.
snap If set, snap to this number of pixels during transformations.
spotHighlight (PathNode) Set to true to darken the entire document except for the contents of this closed shape. See Using Spot Highlight
strokeStyle The HTML or CSS colour code of the outline of a shape. For the brush tool, you may set this to “erase” to create an eraser.
text The text of the textNode or centered in a path.
url (ImageNode) The url to the image.
wrap (TextNode) When set to true, the font size will remain the same when the user stretches the text box. By default, this is set to the value of the multlineText setting, but you can override it in the call to the useTextTool function.
zIndex Nodes with a higher zIndex value are drawn on top of those with a lower one, regardless of the ordering in the document. Default: 0.

Configuration settings

var ctx = Zwibbler.create("myDivId", {
    showPropertyPanel: false,
    showColourPanel: true,
    debug: true
});

// set a setting afterwards:
ctx.setConfig("snap", 10);

When a zwibbler instance is created using Zwibbler.create(), the first parameter is the identifier of the DIV element to contain Zwibbler. The second parameter is a javascript object containing configuration settings. For example:

Use the configuration setting playground to experiment with the settings.

You can quickly override a configuration setting without changing the source code. Simply append the setting to the url. For example:

http://zwibbler.com/#showDebug=true

allowResize setting

Determines whether the user is allowed to resize items in the drawing.

Values

Value Description
true (Default) Allow the user to resize shapes
false Do not allow the user to resize shapes

allowSelectBox setting

On a touch screen, if you are in the pick tool and you touch the screen, you will draw a blue box to select shapes. This box is referred to as the selection box. However, if zwibbler takes up most of the screen, the user will be unable to scroll the web page. You can turn off the selection box with this setting, thus allowing the user to scroll the web page when they swipe against the drawing.

Values

Value Description
true (Default) Enable the selection box.
false Disable the selection box.
"auto" Enable the selection box on non-touch screens and in cases where the web page completely fits in the window, so that there never is a need to scroll

allowTextInShape setting

This allows the user to write text inside a closed shape, when the user double clicks or uses the tool on a closed shape. Note that this can be annoying if it’s not what the user intended.

Values

Value Description
true (Default) Enables user to write text inside a closed shape.
false Disables user to write text inside a closed shape.

allowZoom setting

This option allows the user to zoom in and out using the keyboard or pan tool.

Values

Value Description
true (Default) Enables zooming in and out using keyboard / pan tool.
false Disables zooming in and out. You can only zoom using the setZoom function

autoPickTool setting

When a shape is drawn, Zwibbler will return to pick tool immediately.

Values

Value Description
true (Default) Revert back to pick tool once shape is drawn.
false Allow user to draw shapes of same type once shape is drawn.

background setting

Set the background of a canvas.

Values

Value Description
"clear" (Default) Renders the background transparent.
"grid" A grid will be used as a background with the dimensions of each square given in the gridSpacing option.
colour The colour will be used as the background colour for the canvas. Set it to "white" if you do not want to save transparent images. The supported formats are hex or rgb() or rgba() or a standard CSS colour name.

backgroundImage setting

Sets the background image for the canvas.

Values

Value Description
null (Default) No image.
URL The image will be used as the background image

colourPicker setting

Determines the type of colour picker to use in the property panel.

Values

Value Description
"wheel" (Default) Uses the colour wheel.
"palette" Uses a colour palette shown with predefined colours (Colours are chosen from the colourPalette setting)

colourPalette setting

Sets which colours to display in the colour panel. You may set it to the value “auto”, or an array of colour names, or a comma-separated list of colour names. Use the special colour value “rgba(0,0,0,0.0)” to indicate fully transparent, and “rgba(0,0,0,0.5)” to indicate partially transparent in the current colour. All other colour values will be used literally.

Default

"auto"

defaultArrowSize setting

Controls the size of arrowhead in the arrow tool.

Values

Value Description
15 (Default) Default size for the arrowhead.
number The offset in pixels from the tip of the arrow head to the bottom of the arrow head along the shaft.

defaultArrowStyle setting

Controls the style of the arrowhead in the arrow tool.

Values

Value Description
"simple" (Default) An open arrow head is drawn.
"solid" The arrow head will be filled with a solid colour, using the path node’s strokeStyle property.

defaultArrowXOffset setting

Controls the size of the arrowhead when an arrow is drawn.

Value Description
null (Default) Use the value of defaultArrowSize

See Properties of Nodes.

defaultBold setting

The default font weight for new text.

Values

Value Description
false (Default) Does not display emboldened text.
true Displays emboldened text.

defaultBrushColour setting

Sets the default brush colour when the brush tool is used.

Values

Value Description
"#000000" The default brush colour
colour Supported Formats: hex or rgb() or rgba() or a standard CSS colour name

defaultBrushWidth setting

Sets the default brush width, in pixels.

Values

Value Description
10 The default brush width
number The width in pixels

defaultFillStyle setting

Sets the default fill colour.

Values

Value Description
"e0e0e0" default
colour The colour value to use for filled shapes. To fill with a transparent colour, use “rgba(0,0,0,0.0)”

defaultFont setting

Sets the default font to be used for text.

Values

Value Description
"arial" The default font for text.
font Sets the default font to be used for text

defaultFontSize setting

Sets the default font size to be used for text.

Values

Value Description
20 The default font size for the text.
fontSize Sets the default font size for the text.

defaultItalic setting

The italic setting for new text.

Values

Value Description
false (Default) Text is not italicized.
true Italicizes the text.

defaultLineWidth setting

Sets the default line width to be used for outlines of shapes, other than the brush tool.

Values

Value Description
2 The default line width for the outlines of shapes.
number Sets the line width for outlines of shapes.

defaultPaperSize setting

Sets the paper size for the document.

To set a custom size, use the ZwibblerContext.setPaperSize(width, height) function and pass the width and height as numbers. Otherwise, use one of these values for the default.

Values

Value Description
"none" (Default) The document is always sized large enough to fit all objects.
"letter" Sets the document paper size to letter.
"legal" Sets the document paper size to legal.
"11x17" Sets the document paper size to 11 by 17.
"tabloid“” Sets the document paper size to tabloid.
"A1" Sets the document paper size to A1.
"A2" Sets the document paper size to A2.
"A3" Sets the document paper size to A3.
"A4" Sets the document paper size to A4.

defaultRoundRectRadius setting

Sets the rounding radius for paths. Whenever two connected lines are drawn, the corner is smoothed by this amount. This is a different algorithm than for curves, which are set using the defaultSmoothness setting.

Values

Value Description
10 (Default) The default rounding radius for paths.
number Sets the default rounding radius for paths.

defaultSmoothness setting

Sets the default smoothness for the curve tool.

Values

Value Description
smooth (Default) A medium amount of smoothness for the curve tool.
smoothest The smoothest option for the curve tool.
sharp Sharp corners when drawing curves
sharper Sharper corners.
sharpest The curve tool has very sharp corners.

defaultStrokeStyle setting

Sets the default colour for the outlines of the shapes.

Values

Value Description
"#000000" Default
colour hex or rgb() or rgba() or a standard CSS colour name.

defaultTextBackground setting

Sets the default background colour for the text.

Values

Value Description
"rgba(0,0,0,0.0)" Default
colour hex or rgb() or rgba() or a standard CSS colour name.

defaultTextFillStyle setting

Sets the default colour for the text.

Values

Value Description
"#000000" Default
colour hex or rgb() or rgba() or a standard CSS colour name.

defaultTextStrokeStyle setting

Sets the default outline colour for the text.

Values

Value Description
`“#000000” Default
colour hex or rgb() or rgba() or a standard CSS colour name.

defaultTextLineWidth setting

Sets the default outline width for the text.

Values

Value Description
0 Default
number Sets the default outline width for the text.

defaultZoom setting

Sets the default zoom level of the drawing area.

Values

Value Description
1.0 default
"width" Zoom to the width of the document.
"page" Zoom to fit the entire document.
number Set the zoom factor between 0.0 and 1.0

drawShapeStyle setting

Sets the default style of drawing circles and polygons.

Values

Value Description
"box" (Default) Allows the user to draw ellipses and shapes from the top-left to bottom right, like in PowerPoint.
"radial" Allows the user to draw perfect circles and regular shapes by dragging the centre to the outer edge.

fonts setting

var ctx = Zwibbler.create("#mydiv", {
    fonts: ["Arial", "Times New Roman", "Courier New"]
});

Sets the fonts available for use in text.

Values

Value Description
[“Arial”, “Times New Roman”] The default font array available for use.
array To use custom fonts, make them available in the CSS3 and refer to their names here in this array.

gridBlocks setting

Sets the number of blocks in each grouping when background is set as grid.

Values

Value Description
10 (Default) Draws grouping of 10 by 10 squares with thicker ink.
0 All grid squares are drawn with the same line thickness.

gridColour setting

Sets the colour of lines when background is set as grid.

Values

Value Description
"#cccccc" Default
colour hex or rgb() or rgba() or a standard CSS colour name.

gridSpacing setting

Sets the dimension of each square when background is set as grid.

Values

Value Description
20 Default
number Sets the default dimension of each square.

imageFolder setting

Sets the path for directory of images for the toolbar.

Values

Value Description
"$SCRIPT" (Default) Use “$SCRIPT” in the path to refer to the place where zwibbler2.js is placed. For example, to store the .png images in a folder called “images”, which is in the folder where zwibbler2.js is stored, then set it to “$SCRIPT/images”.

language setting

Sets what language in which Zwibbler displays prompts and hint text.

Values

Value Description
"en" Default
string You may choose es for Spanish, or fr for french. Other languages may be defined using the addToLanguage API.

leaveTextToolOnBlur setting

When the text box is displayed for text entry, this property determines whether it should immediately disappear when the user clicks anywhere else.

Values

Value Description
false (Default) Do not hide the text box when it loses focus.
true Immediately hide the text entry box when it loses focus.

multilineText setting

Sets newlines to be allowed in the text tool.

Values

Value Description
false (Default) Disables newline in the text tool.
true Enables newline in the text tool.

See also

The wrap property

nudge setting

Sets the x and y offset to use when user moves the shapes using the cursor keys.

Values

Value Description
10 Default
number Sets the default nudge value.

To change the offset when the Ctrl key is held, use preciseNudge

outsidePageColour setting

Set the colour of the area outside the page, when pageView is set to true.

Values

Value Description
"#808080" Default
colour hex or rgb() or rgba() or a standard CSS colour name.

pageBorderColour

Sets the colour of the 1 pixel border draw around the paper.

Values

Value Description
"rgba(0,0,0,0.0)" Default
colour hex or rgb() or rgba() or a standard CSS colour name.

pageInflation setting

Sets the minimum size of the gray border around the page when pageView is set to true.

Values

Value Description
20 (Default)

pagePlacement setting

Sets the position of the page when pageView is set to true.

Values

Value Description
"centre" (Default) Centres the page on the screen.
"left" Aligns the page to the left of the screen.

pageShadow setting

Enables or disables the shadow around the page to indicate the borders.

Values

Value Description
true (Default) Enables the shadow around the page, if pageView is enabled.
false Disables the shadow.

pageView setting

Draws the outline of the page.

Values

Value Description
true (Default) Enables the outline around the paper.
false Disables the outline.

pasteOffset setting

Sets the offset in X and Y directions, when pasting items.

Values

Value Description
0 Default
number Sets the default offset when pasting items.

persistent setting

Preserves the document between page loads.

Values

Value Description
false (Default) Does not preserve the document between page loads.
true Preserves the document between page loads. Use the newDocument function to clear it.

preciseNudge setting

Sets the x and y offset to use when the user moves shapes using the cursor keys while holding Ctrl Key.

Values

Value Description
1 Default
number The offset to use when the user moves shapes using cursor keys.

readOnly setting

Disallow the user from interacting with the drawing. When set to true, the drawing acts like an image.

Values

Value Description
false (Default) Allows the user to alter the drawing.
true Disallows the user from altering the drawing.

scrollbars setting

Enables or disables the scrollbars in the document viewing area.

Values

Value Description
true (Default) Scrollbars will appear when document size exceeds the viewing area.
false Scrollbars will not appear.

setFocus setting

Determines whether Zwibbler grabs the keyboard focus when the HTML page is loaded.

Values

Value Description
true (Default) Zwibbler will obtain the keyboard focus when created and when the user clicks in the drawing area. As a side effect, the browser will scroll Zwibbler to be in view of the page.
false This will set the keyboard focus to false. Zwibbler will be unable to intercept any keyboard commands. For keyboard support, you will need to set the focus manually using the focus function.

showArrowTool setting

Determines whether to show the arrow tool in the built-in toolbar.

Values

Value Description
true (Default) Displays the arrow tool.
false Hides the arrow tool.

showBrushTool setting

Determines whether to show the brush tool in the built-in toolbar.

Values

Value Description
true (Default) Displays the Brush tool.
false Hides the Brush tool.

showCircleTool setting

Determines whether to show the circle tool in the built-in toolbar.

Values

Value Description
true (Default) Displays the Circle tool.
false Hides the Circle tool.

showColourPanel setting

Determines whether to show the colour palette at the bottom of the canvas.

Values

Value Description
true (Default) Displays the Colour Panel.
false Hides the Colour Panel.

showCopyPaste setting

Determines whether to show the copy / paste buttons on the built-in toolbar.

Values

Value Description
true (Default) Displays the copy and paste buttons.
false Hides the copy and paste buttons.

showCurveTool setting

Determines whether to show the curve tool in the built-in toolbar.

Values

Value Description
true (Default) Displays the curve tool.
false Hides the curve tool.

showDebug setting

Determines whether to show debugging information to the right of the canvas. This can help with diagnosing problems and viewing logging information about Zwibbler.

Values

Value Description
false (Default) Hides the Zwibbler Debug Area.
true Displays the Zwibbler Debug area.

showFontNameProperty setting

Determines if the user is allowed to choose a font in the property panel.

Values

Value Description
true (Default) Allows the user to choose font from the property panel.
false Disallows the user from choosing the font.

showFontSizeProperty setting

Determines if the user is allowed to choose a font size in the property panel.

Values

Value Description
true (Default) Allows the user to edit font size from the property panel.
false Disallows the user from editing the font size.

showHints setting

Displays a set of hints in the top left to help users draw lines and curves.

Values

Value Description
true (Default) Displays default set of hints in the top left.
false If you would like to show the hints some other way, set to false, and listen for the “hint” event.

showKeyboardHelp setting

Show or hide information about the keyboard commands in the property panel.

Values

Value Description
true (Default) Displays the keyboard help information.
false Hides the keyboard help information.

showLineTool setting

Determines whether to show the line tool in the built-in toolbar.

Values

Value Description
true (Default) Show the line tool button
false Hide the line tool button

showMoveToFrontBack setting

Determines whether to show the move to front and send to back buttons in the built-in toolbar.

Values

Value Description
false (Default) Show the buttons for “bring to front” and “send to back”.
true Hide the buttons for “bring to front” and “send to back”.

showPageSelector setting

Shows the page selector, which allows the user to insert, delete, and switch between pages. Consider also setting the pageView and defaultPaperSize options.

Values

Value Description
false (Default) Disables the page selector.
true Enables the page selector.

showPageSelectorControls setting

Allow the user to add or remove pages using the built-in page selector.

Values

Value Description
true (Default) Allow the user to add or remove pages.
false Prevent the user from adding or removing pages.

showPickTool setting

Determines whether to show the selection tool in the built-in toolbar.

Values

Value Description
true (Default) Shows the pick tool button.
false Hides the pick tool button.

showPropertyPanel setting

Display the property panel to the right of drawing area.

Values

Value Description
false (Default) Displays the property panel at it’s usual place.
true Do not show the property panel.

showRoundRectTool setting

Determines whether to show the rounded rectangle tool in the built-in toolbar.

Values

Value Description
false (Default) Do not show the rounded rectangle tool.
true Show the rounded rectangle tool

showShapeBrushTool setting

Determines whether to show the magic shape brush tool in the built-in toolbar.

Values

Value Description
false (Default) Do not show the magic shape brush
true Show the magic shape brush.

showSloppinessProperty setting

Allow the user to edit the Sloppiness property from the Property Panel.

Values

Value Description
true (Default) Allows the user to edit the Sloppiness property.
false Prevent the user from editing the Sloppiness property.

showSmoothnessProperty setting

Allow the user to edit the Smoothness property from the Property Panel.

Values

Value Description
true (Default) Allows the user to edit the Smoothness property.
false Prevent the user from editing the Smoothness property.

showSquareTool setting

Determines whether to show the square tool in the built-in toolbar.

Values

Value Description
true (Default) The square tool is shown.
false The square tool is hidden.

showTextTool setting

Determines whether to show the text tool in the built-in toolbar.

Values

Value Description
true (Default) The text tool is shown
false The text tool is hidden.

showToolbar setting

Determines whether to show the built-in toolbar. This toolbar helps you get up and running quickly. However, most users create their own toolbar so they can customize it more fully.

Values

Value Description
true (Default) Show the built-in toolbar
false Hide the built-in toolbar

showUndoRedo setting

Determines whether to show the undo/redo buttons in the built-in toolbar.

Values

Value Description
true (Default) The undo/redo buttons are shown
false The undo/redo buttons are hidden.

singleStrokeBrush setting

Determines the behaviour of the brush tool.

Values

Value Description
false (Default) The brush tool will allow more than one brush stroke after the user releases the mouse, even when autoPickTool is set to false.
true The pick tool is selected after the user releases the mouse.

snap setting

Allows the shapes to snap to a grid with spacing.

Values

Value Description
0 (Default) No snapping is performed.
number This will make all shapes snap to the grid with the given spacing.

spotHighlightColour setting

Sets the colour of background used for the Spot Highlight feature.

Values

Value Description
"rgba(0,0,0,0.4)" Default
colour This should be a partially transparent colour. Hex or rgb() or rgba() or a standard CSS colour name is supported.

spotHighlightZIndex setting

Sets the z-index of the spot-highlight mask. It will cover shapes with a lower zIndex property, and those with a higher zIndex property will be drawn on top.

Values

Value Description
0 (Default) The default z-index for the spot-highlight mask.
number Sets the zIndex for the spot highlight mask.

symmetry setting

Gives the drawing a kaleidoscopic effect around the centre of the screen. The number of axes of symmetry are given by this value.

Values

Value Description
0 default
number Sets the symmetry for the drawing.

toolbarButtonSize setting

When showToolbar is true, this controls the dimensions of the buttons in the built-in toolbar.

Values

Value Description
50 default
number Sets the dimensions of buttons, in pixels.

useTouch setting

Determines whether Zwibbler is optimized for touch screens. When touch is enabled, the selection handles and colour palette are larger, and a trash can appears when shapes are selected so that the user can delete them without using the keyboard.

Values

Value Description
"auto" (Default) By default, Zwibbler automatically detects touch screens. However, many browsers advertise support for touch screens even when they don’t have one.
true Forces touch to be on.
false Forces touch to be off. Note: The user will still be able to interact using touch, but the user interface will not be optimal.

Keyboard Configuration

You can change the keyboard configuration in the initial call to Zwibbler.create(). The key description is easy to learn. For example, “Ctrl+Shift+Alt+Z”. Case or ordering does not matter. Spaces are ignored. Multiple key combinations for the same action can be separated by commas.

Zwibbler understands these keys in a key description

Option Default Description
keyBringToFront Home When pressed, selected shapes are move to front.
keyCancel ESC Cancel text entry.
keyCopy Ctrl+C, ⌘+C Copy to Zwibbler clipboard.
keyCurveTool C Draw curves.
keyCut Ctrl+X, ⌘+X, Shift+Delete Cut the selection.
keyDelete Delete, Backspace Delete the selection.
keyDown Down,Ctrl+Down Nudge a shape in the downward direction
keyDuplicate Ctrl+D Duplicate the selection.
keyEnter Enter The enter key
keyLeft Left Nudge a shape in the left direction
keyGroup Ctrl+G Group the selected shapes.
keyLineTool L Activate the line tool.
keyMoveDown PageDown Move the selected shapes under other shapes.
keyMoveUp PageUp Move the selected shapes up from under other shapes.
keyNextPage Shift+PageDown Switch to next page.
keyPaste Ctrl+V, ⌘+V, Shift+Insert Paste from Zwibbler clipboard.
keyPrevious Left,Up
keyPreviousPage Shift+PageUp Switch to the previous page.
keyRedo Ctrl+Shift+Z Redo.
keyRight Right
keySelectAll Ctrl+A Select all on the current page.
keySelectNone ESC When shapes are selected, deselect them.
keySendToBack End Send selected shapes to the back.
keyUndo Ctrl+Z Undo.
keyUngroup Ctrl+Shift+G Break apart any selected groups of shapes.
keyZoomIn + Zoom in.
keyZoomOut - Zoom out.
keyZoomNormal = Zoom to 100%.
keyZoomToPage F4 Zoom to view entire document.
keyZoomToWidth Shift+F4 Zoom to document width.

Events

You can be notified when certain events happen, by calling the on function

document-changed

ctx.on("document-changed", function() {
    if (ctx.dirty()) {
        // enable save button
    } else {
        // disable save button
    }
});

A supported event is “document-changed”. It is triggered whenever the document changes for any reason. This can be used, for example, to display undo/redo buttons correctly by information about keyboard commands is shown in the property calling canUndo and canRedo.

blur

This event is sent when Zwibbler loses the keyboard focus due to pressing the ESC key. For keyboard accessibility, The application should move the keyboard focus back to the currently used tool on the toolbar, if any.

hint


// disable showing hints on the canvas
ctx.setConfig("showHints", false);

ctx.on("hint", function(text) {
    $("#hint-text").text(text);
});

The “hint” event is sent when the user is drawing lines. The text passed to the function will help guide the user through the procedure of drawing lines and curves.

selected-nodes

ctx.on("selected-nodes", function() {
    var nodes = ctx.getSelectedNodes();

    // show/hide buttons based on what is selected.
});

The “selected-nodes” event is sent when the selection has changed. You can use getSelectedNodes to obtain the ids of the nodes.

set-page

ctx.on("set-page", function(pageNumber) {
    console.log("User switched to page %s", pageNumber);
});

The “set-page” event is sent whenever the current page number changes, while not in a transaction. The parameter is the zero-based page number.

node-clicked

ctx.on("node-clicked", function(node) {
    var tag = ctx.getNodeProperty(node, tag);
    if (tag) {
        alert("You clicked on a special node");
    }
});

The “node-clicked” event is sent when a node is clicked. The first parameter of the callback is the id of the clicked node.

double-click

// Below is an example. However, this behaviour may be best implemented using 
// a custom tool.
ctx.on("double-click", function(x, y, node) {
    if (node && ctx.getNodeProperty(node, "tag")) {
        alert("You clicked on the X");
    } else {
        // Insert an image at the given point.
        ctx.beginTransaction();
        var nodeid = ctx.createNode("ImageNode", {
            url: "x-marks-the-spot.png"
        });
        ctx.translateNode(nodeid, x, y);
        ctx.commitTransaction();
    }
}

The “double-click” event is sent when the canvas is double clicked and the pick-tool is active. The first two parameters, x, y, are the coordinates in the document (not the screen). The last parameter, nodeid, is the node that was clicked, if any. If no node was clicked, it is null.

tool-changed

ctx.on("tool-changed", function(toolname) {
    $(".tool").removeClass("selected");
    $(".tool-" + toolname).addClass("selected");
});

The “tool-changed” event is sent when the current tool changes for any reason. The application can use this to highlight buttons on a custom toolbar. The parameter given to the callback is the name of the tool, which can be:

See also

createToolbar function, getCurrentTool function

resource-loaded

The “resource-loaded” event is sent when an image is loaded. If you have drawn the document using Zwibbler.render() or created an image of it, you may have to do it again when you get this event as new images or fonts are loaded.

See Also

onComplete

“nodes-added”, “nodes-removed”, and “nodes-changed”

function showNodes(nodes) {
    for(var i = 0 ; i < nodes.length; i++) {
        console.log("Node id %s is %s", nodes[i], ctx.getNodeType(nodes[i]));
    }
}

ctx.on("nodes-added", function(nodes) {
    console.log("Added %s nodes", nodes.length);
    showNodes(nodes);
});

ctx.on("nodes-removed", function(nodes) {
    console.log("Removed %s nodes", nodes.length);
    showNodes(nodes); // error. note types are no longer available.
});

ctx.on("nodes-changed", function(nodes) {
    console.log("Changed %s nodes", nodes.length);
    showNodes(nodes);
});

The “nodes-added”, “nodes-removed”, and “nodes-changed” events are sent whenever the user changes the document. The parameter is an array of the nodes that have changed. Note that when nodes are removed, you cannot retrieve information about them because they no longer exist.

These events are also fired when the user uses the undo/redo functions, as the nodes disappear and reappear.

draw

ctx.on("draw", function(canvasContext) {
    // undo the zoom and scrolling so the overlay does not move
    canvasContext.setTransform(1, 0, 0, 1, 0, 0);

    // overlay some text on the drawing
    canvasContext.font = "50px Arial";
    canvasContext.fillStyle = "rgba(0, 0, 0, 0.3)";
    canvasContext.fillText("DRAFT", 0, 0);
});

The “draw” event is sent whenever the document is drawn. The parameter of the function is the canvas rendering context, already transformed based on the zoom and scrolling. You can overlay things on top of the canvas by handling this event.

convert-dom-request

When you receive this, you must call the setDomNode function to give Zwibbler a newly HTML element to overlay onto the canvas.

Parameters

Parameter Description
id The id of the zwibbler node
dataString The data property of the node provided when you created it. Use this to create the appropriate HTML element.

See also

Including DOM elements in the drawing

Zwibbler Context Functions

var ctx = Zwibbler.create("#mydiv", {
    showToolbar: true
});

// call functions on the zwibbler context.

Here are the functions that you can call on a ZwibblerContext.

abortTransaction

ctx.beginTransaction();
ctx.createNode("ImageNode", {
    url: "http://zwibbler.com/logo.png"
});
ctx.abortTransaction();

Discards all actions since the last call to beginTransaction

This function is not aware of nested calls to beginTransaction so it will throw an error if you use it this way. If you are using abortTransaction and have nested calls, please contact Zwibbler support and I will implement this the correct way.

addPage

ctx.addPage();

Adds a page to the end of the document.

addToLanguage

ctx.addToLanguage("fr:click-to-place-first-point-of-line:Clickez pour placer le premier point de la ligne")

en:click-to-place-another-point-or-double-click-to-end-the-line:Click to place another point, or double-click to end the line.
es:click-to-place-another-point-or-double-click-to-end-the-line:Haga clic para colocar otro punto, o doble clic para finalizar la línea

en:click-to-place-first-point-of-line:Click to place first point of line
es:click-to-place-first-point-of-line:Haga clic para colocar el primer punto de la línea

en:click-to-set-the-end-of-the-line:Click to set the end of the line
es:click-to-set-the-end-of-the-line:Haga clic para colocar el extremo de la línea

Sets the internationalized text for a text string in a specific language. The language strings used by Zwibbler are given in the LanguageData.coffee file in the source code. You can set more than one string at the same time by separating them with newline characters. As an example, here are how the line drawing prompts are defined. You can add or modify the french language by calling.

Parameters

Parameter Description
text The internationalized text for a text string in a specific language.

When a language is defined, and you set the “language” configuration option, this language will be used for all prompts displayed by Zwibbler.

beginTransaction

ctx.beginTransaction();

ctx.translateNode(ctx.getSelectedNodes(100, 10));

// user will be unable to undo the operations.
ctx.commitIrreversibleTransaction();

When called, all subsequent operations will be stored but not executed until commitTransaction, commitIrreversibleTransaction or abortTransaction is called.

In addition, the actions will be stored in the undo() stack as a single unit, so they will all be undone if the user clicks “undo”.

You may have nested calls to beginTransaction.

bringToFront

ctx.bringToFront();

Move the selection to the front.

See also

moveDown, sendToBack

canRedo

ctx.on("document-changed", function() {
    if (ctx.canRedo()) {
        // enable the redo button
    } else {
        // disable the redo button
    }
});

Use this function to determine if it is possible to redo an action.

Return value

Returns true if it is possible to redo an action.

See also

canRedo, dirty, Manipulating the Undo Stack

canUndo

ctx.on("document-changed", function() {
    if (ctx.canUndo()) {
        // enable the undo button
    } else {
        // disable the undo button
    }
});

Use this function to determine if it is possible to undo an action.

Return value

Returns true if it is possible to undo an action.

clearSelection

ctx.clearSelection();

Unselect everything.

clearUndo

ctx.newDocument();

// place some images and lines in the drawing in a separate layer

// make the changes undo-able by user
ctx.clearUndo();

Clears the undo stack.

commitIrreversibleTransaction

ctx.beginTransaction();
// ... make some changes
// The user will not be able to undo these changes.
ctx.commitIrreversibleTransaction();

Performs all actions since the last call to beginTransaction, but bypasses the undo() stack. The actions will not be undo-able by the user.

commitTransaction

ctx.beginTransaction();

// insert an image in the document and move it to 100, 100. The user will
// be able to undo these two changes as a single unit.

var node = ctx.createNode("ImageNode", {
    url: "http://zwibbler.com/logo.png" 
});

ctx.translateNode(node, 100, 100);

ctx.commitTransaction();

Performs all actions since the last call to beginTransaction and stores them on the undo stack as a single entry.

copy

ctx.paste(ctx.copy());

Copy the current selection. If justReturn is set to true, the value is merely returned as a string. Otherwise, it is also placed into the Zwibbler clipboard, which is stored in HTML localStorage.

Parameters

Parameter Description
justReturn Don’t store in the zwibbler clipboard. Just return the snippet.
nodes Optional array of node ids to copy. If not specified, the current selection is used.

Return value

A string representing the copied shapes. This can be stored in your database or inserted into the document using the paste function.

createGroup

var group = ctx.createGroup(ctx.getSelectedNodes());

Group the given node ids together. Returns the id of the group. Whenever one element of a group is selected by the user, the other elements are selected as well, so they appear to be a single shape.

Parameters

Parameter Description
ids Send a group of node ids together.

Return value

Returns the id of the group. This id can be used to delete it and all members of the group at once. This is often called in combination with getSelectedNodes to obtain the ids.

createNode

ctx.beginTransaction();
var node = ctx.createNode("TextNode", {
    text: "Hello world",
    fontSize: 50,
    fontName: "Arial"
});
ctx.translateNode(node, 100, 100);
ctx.commitTransaction();

Create a node of the given type and properties.

Parameters

Parameter Description
type The node type
properties The properties

Valid node types are:

Return value

Returns the id of the node. This id can be used to delete or set properties.

You can specify a transformation matrix as a property in a six element array, [a, b, c, d, dx, dy] where a and b are the first row of the matrix, c, d are the second row, and dx and dy are the displacement.

createPath

// insert a square into the document.
var commands = Zwibbler.PathCommands();
commands.moveTo(100, 100);
commands.lineTo(200, 100);
commands.lineTo(200, 200);
commands.lineTo(100, 200);
commands.lineto(100, 100);
commands.close();

ctx.createPath(commands.toArray());

Alternatively

var nodeid = ctx.createNode("PathNode", {
    commands: commands
});

Creates a PathNode using the given array of path commands.

Parameters

Parameter Description
commands An array of path commands

Return value

Returns the id of the node. This id can be used to delete or set properties.

createShape

// create a triangle
var node = ctx.createShape([150, 100, // top
                            200, 200, // right corner
                            100, 200  // left corner
]); 

Creates a closed shape with the given coordinates.

Parameters

Parameter Description
points_arr The array contains the x, y points one after another, and must have an even number of elements. It must have at least 3 points (six elements).

Return value

Returns the id of the node. This id can be used to delete or set properties.

createToolbar

CSS

#toolbar {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
}

.zwibbler-button {
    width: 50px;
    height: 50px;
}

Javascript

ctx.createToolbar("#toolbar", [
    {
        title: "Pick tool",
        image: "icon-pick-tool.png",
        toolName: "pick",
        onclick: function() {
            ctx.usePickTool();
        }
    }, {
        title: "Large brush",
        image: "icon-large-brush.png",
        onclick: function() {
            ctx.useBrushTool({
                lineWidth: 20
            });
        }
    }, {
        title: "Small brush",
        image: "icon-small-brush.png",
        onclick: function() {
            ctx.useBrushTool({
                lineWidth: 5
            });
        }
    }, {
        title: "Circle",
        toolName: "circle",
        image: "icon-circle.png",
        onclick: function() {
            ctx.useCircleTool();
        }
    }, {
        title: "Undo",
        image: "icon-undo.png",
        onclick: function() {
            ctx.undo();
        }
    }, {
        title: "Redo",
        image: "icon-redo.png",
        onclick: function() {
            ctx.redo();
        }
    }
]);

Allows you to easily create a custom toolbar inside your own div element. The function will place <a> elements inside the div, with the specified image, and when they are clicked call functions that you define.

You must style the CSS class .zwibbler-button to have a fixed size in your CSS, or the buttons will not appear.

Parameters

Parameter Description
div The HTML div or selector in which to place the toolbar items
items An array of toolbar descriptors

Toolbar descriptor

Pass in an array of toolbar descriptors to define the toolbar

Property Description
onclick Function to call when the button is clicked. The this context in which the function is called is set to the HTML element that was clicked.
title The hint text to show when the user hovers their mouse over the button.
background The text to set the CSS background of the button
image (If background is not provided) The background image of the element.
toolName (Optional) The name of the tool. When this tool is active, the ‘zwibbler-selected’ class will be added to the toolbar button. If you style this class using css, it will be highlighted. See the tool-changed event
html (Optional) A text string describing the inner HTML of the button. This can be useful to use a font based icon, such as font-awesome.

cut

ctx.cut();

Cut the current selection. This copies it to the Zwibbler clipboard in localStorage and deletes the selection. It also returns the selection as a string, as in copy.

Return value

A string. You can store this and later paste it into a Zwibbler document.

deleteNode

ctx.deleteNode(ctx.getSelectedNodes());

Delete the given node. The user can undo this action.

Parameters

Parameter Description
node / array of nodes Pass a single node or an array of nodes and they will be deleted.

deleteNodes

ctx.deleteNodes(ctx.getSelectedNodes());

Equivalent to deleteNode

deletePage

ctx.deletePage(ctx.getCurrentPage());

Delete given page using the zero-based page number. The user can undo this action.

Parameters

Parameter Description
index The zero-based page number that you want to be deleted.

deleteSelection

ctx.deleteSelection();

Deletes the currently selected shapes.

destroy

ctx.destroy();
ctx = null;

Destroys this instance of Zwibbler and frees all memory it uses.

dirty

if (!ctx.dirty() || confirm("Do you want to start over?")) {
    ctx.newDocument();
}

Sets or retrieves the document dirty flag. The document is marked dirty if it has changed since being created or loaded, or since the last call to dirty(false).

Parameters

Parameter Description
dirtyFlag (Optional) pass true or false to explicitly set the dirty flag. Otherwise, the current value is returned.

Return value

Returns true if the document has unsaved changes.

download

var filename = prompt("Please enter a filename");
if (filename) {
    ctx.download("pdf", filename + ".pdf");
}

Causes the browser to download the current document as an “svg” or “pdf” or “png” file. The format must be one of these. The user will be prompted by the browser to save the file.

Parameters

Parameter Description
format The value can be zwibbler3, svg, pdf, bmp or png file.
filename The filename to save as, including the extension.

draw

ctx.load(myDocumentFromServer);
ctx.onComplete(function() {
    var canvas = document.createElement("canvas");
    var size = ctx.getDocumentSize();
    canvas.width = size.width;
    canvas.height = size.height;
    ctx.draw(canvas.getContext("2d"));
    document.body.appendChild(canvas);
});

Draws the document to the given HTML5 canvas context.

Parameters

Parameter Description
ctx The value can be svg, pdf or png file.
options Options is a javascript object containing options. If “page” is in the object, then that page number is drawn.

duplicate

ctx.duplicate();

Duplicates the current selection.

editNodeText

var selection = ctx.getSelectedNodes();
if (selection.length) {
    ctx.editNodeText(selection[0]);
}

If the given node can contain text, then immediately enter text edit mode on that node, allowing the user to change the text.

findNode

var markerNode = ctx.findNode("mymarker");

Returns the id of the first node with the property “tag” equal to the tag. If there is no such node, then null is returned. The tag property is for your use and it can be set with setNodeProperty or createNode.

Parameters

Parameter Description
tag Pass the tag value of the Node that you want to find.

Return value

The node id, or null if no node was found.

findNodes

var markerNodes = ctx.findNode("mymarker");

Same as findNode, but this function returns an array of nodes.

Parameters

Parameter Description
tag Pass the tag value that you want to find.

Return value

Array of node ids

flip


// flip the shapes vertically
ctx.flip(90);

// flip the shapes horizontally
ctx.flip(0);

Flip the current selection about the vertical line passing through its centre, that is rotated the given number of degrees.

Parameters

Parameter Description
degrees The rotation angle in degrees of the line of reflection. Use 0 for a vertical line.
centreX (optional) If given, this is used instead of the centre of the selection.
centreY (optional) If given, this is used instead of the centre of the selection.

flipNodes

// flip the entire page horizontally about its centre.
var size = ctx.getDocumentSize();
ctx.flip(ctx.getAllNodes(), 
    size.x + size.width / 2, 
    size.y + size.height / 2);

Flip the given node or nodes. See also flip.

Parameters

Parameter Description
node The node or array of nodes that you want to flip.
degrees The amount of degrees you want to rotate the shape.
centreX (optional) If given, this is used instead of the centre of the nodes
centreY (optional) If given, this is used instead of the centre of the nodes.

focus

ctx.focus();

Give Zwibbler the keyboard focus, allowing the use of keyboard shortcuts. This may cause the browser to scroll Zwibbler into view. It is necessary to call this function only if you set the setFocus setting to false.

Parameters

Parameter Description
showKeyboardCursor (Optional) When set to true, show the keyboard cursor. The user will then be able to draw using the cursor keys and the Enter key. The user can dismiss it using the ESC key.

generatePalette

ctx.generatePalette("#colours", 20);

Generate a colour palette inside the given div element. A mix of exactly 256 colours will be automatically generated, and the colour swatches will work when clicked by the user.

Parameters

Parameter Value
div The HTML div or selector to contain the colour palette
size The size of each colour swatch.

getActiveLayer

console.log(ctx.getActiveLayer());

Returns the active layer set by setActiveLayer. If no layer has been set, this is “default”

getAllNodes

var nodes = ctx.getAllNodes();
for(var i = 0; i < nodes.length; i++) {
    // process each node.
}

Returns an array of all the nodes on the current page.

See also

getLayerNodes

getBackgroundImage

var url = ctx.getBackgroundImage();

if (url !== null) {
    console.log("The background image is " + url);
}

Returns the URL of the background image for the document, or null if none is configured.

getBoundingRectangle

var rect = ctx.getBoundingRectangle(ctx.getSelectedNodes());

console.log(rect.x, rect.y, rect.width, rect.height);

Returns the bounding rectangle for the given nodes. The rectangle has x, y, width, and height properties.

Parameters

Parameter Description
ids The node or nodes that you want to get the bounding Rectangle.

getCanvasScale

var scale = ctx.getCanvasScale();

Returns the current scale (zoom) factor of the drawing. The result is always a number.

getConfig

// Get the current font size for new text nodes
var fontSize = ctx.getConfig("defaultFontSize");

Retrieves the value of a configuration parameter.

Parameters

Parameter Description
name Name of the Option.

Return value

A string or number or array with the value of the configuration parameter.

See also

setConfig, Configuration settings

getCurrentPage

var page = ctx.getCurrentPage();

Returns the zero-based page number.

getCurrentTool

var toolName = ctx.getCurrentTool();

Gets the name of the current tool. See the “tool-changed” event for details.

getDocumentCoordinates

var point = ctx.getDocumentCoordinates(0, 0);

console.log("The upper left of the drawing is at %s, %s on the web page",
    point.x, point.y);

Given the coordinates on the web page, returns the corresponding {x, y} coordinates in the document.

Parameters

Parameter Description
x The x coordinate on the web page.
y The y coordinate on the web page.

See also

getScreenCoordinates function

getDocumentSize

var rect = ctx.getDocumentSize();

console.log("The page size is: ",
    rect.x, rect.y, rect.width, rect.height);

Returns an object containing the x, y, width, and height of the document. If you set a document size or paper size is set, that size is used. Otherwise, this is the extended to cover all the shapes in the document.

getDrawingRectangle

var rect = ctx.getDrawingRectangle();

console.log("The drawing is contained in the rectangle: ",
    rect.x, rect.y, rect.width, rect.height);

Returns an object containing the x, y, width, and height, left, right, top, bottom of the document. Unlike the getDocumentSize function, the paper size is ignored and this is the actual extents needed to cover all the shapes objects in the document.

getFillColour

var colour = ctx.getFillColour();

Returns the default fill colour for shapes drawn in the future. This value is set using setColour

getLanguageString

alert(ctx.getLanguageString("click-to-plage-first-point-of-line"));

Return the translation of the key in the current language, as set by the configuration. See also the addToLanguage function.

Parameters

Parameter Description
key The key that you want translated in current language. The full list of keys can be found in the Language.coffee file of the source distribution.

getLayers

var layers = ctx.getLayers();
for(var i = 0; i < layers.length; i++) {
    console.log("Layer %s: %s", i, layers[i]);
}

Returns a list of the names of the layers in the document, as an array of strings.

getLayerNodes

var nodes = ctx.getLayerNodes("default");
for(var i = 0; i < nodes.length; i++) {
    // process each node.
}

Returns an array of the node ids in the layer of the given name.

Parameters

Parameter Description
layerName The layer name, whose nodes you want to retrieve.

See also

Protecting parts of documents with layers

getNodePageNumber

var pageNumber = ctx.getNodePageNumber(nodeid);
var pageNode = ctx.getPageNode(pageNumber);

Returns the zero-based page number of the given node, or undefined if it does not exist.

getNodeProperty

var lineWidth = ctx.getNodeProperty(node, "lineWidth");

Returns the value of the property of the given node.

Parameters

Parameter Description
id The ID of the node.
property The property of the node to be retrieved. See Node Properties

getNodeRectangle

var rect = ctx.getBoundingRectangle(ctx.getSelectedNodes());

console.log(rect.x, rect.y, rect.width, rect.height);

Returns the rectangle of the given node in document coordinates.

Parameters

Parameter Description
id The ID of the node whose rectangle we want retrieved in document coordinates.

getNodeScale

// Make the second node's scale the same as the first.
var scale = ctx.getNodeScale(node1);

ctx.scaleNode(node2, scale.x, scale.y);

Returns the scale component of the node’s matrix. The object returned has x and y values for the scaling in the horizontal and vertical directions.

getNodeType

var nodeType = ctx.getNodeType(node);

Returns the node type of the given node.

getPageCount

var numPages = ctx.getPageCount();
for(var i = 0; i < numPages; i++) {
    ctx.setCurrentPage(i);
    var savedPng = ctx.save("png");
}

Returns the number of pages in the document.

getPageNode

Returns the node id representing the given page, or null if the page does not exist. This should not be used inside of a transaction.

Parameters

Parameter Description
index The zero-based page number.

Return value

If the page exists, returns the node id of the page. Otherwise, returns null.

getPathAsPoints

var parts = ctx.getPathAsPoints(node);
for(var i = 0; i < parts.length; i++) {
    var part = parts[i];
    for(var j = 0; j < part.length; j++) {
        console.log("X: %s, Y: %s", part[j].x, part[j].y);
    }
}

For PathNode only. Returns an array of arrays of points. The reason for multiple arrays is that a path may contain multiple disconnected parts, if it has move_to commands. Each segment has an an array of {x, y} points that approximate the segment. The points are approximate because the curves have been converted to lines for you.

For example, a diagonal line would be [[{x: 0, y: 0}, {x: 100, y:100}]] .

Parameters

Parameter Description
pathNodeId The pathNodeID

getPropertySummary

var summary = ctx.getPropertySummary(ctx.getSelectedNodes());

if ("TextNode" in summary.types) {
    // enable font options, showing the value of 
    // summary.properties.fontName as selected
}

Returns a summary of the types of nodes and their properties. This allows you to easily create property panels to allow the user to change the properties of objects.

Parameters

Parameter Description
nodes Array of the nodes of interest.

Return value

Returns an object with the following fields:

Property Description
types A javascript object with the types of nodes given. For example, if the id of a PathNode is passed in, then the types map will contain an entry PathNode set to true. As a special case for PathNodes, PathNode-open or PathNode-closed will also be in the set, depending on whether it describes an open or closed shape.
properties A combined set of properties and their values. The keys are the property names and the values are the values. If all nodes passed in have the same value for the given property, then the value will be the property value. If the nodes have differing values, the value will be listed as null.

See also

setNodeProperties, setToolProperty

getScreenCoordinates

var viewRect = ctx.getViewRectangle();
var screenRect = ctx.getScreenCoordinates(viewRect.x, viewRect.y, 
    viewRect.width, viewRect.height);
console.log("The drawing on the web page is in rectangle ", 
    screenRect.x, screenRect.y, screenRect.width, screenRect.height);

Given the coordinates in the document page, returns the corresponding {x, y} coordinates in the web page. If a width and height are given, it returns a rectangle with x, y, width, height, left, right, top, and bottom properties.

Parameters

Parameter Description
x The x coordinate in the drawing.
y The y coordinate in the drawing.
width (Optional) The width of the rectangle
height (Optional) The height of the rectangle

See also

getDocumentCoordinates function

getSelectedNodes

var nodes = getSelectedNodes();

Returns an array containing the IDs of each selected node. When expandGroups is set to true, then GroupNodes will not be included. Instead they will be expanded so only their members are included in the results.

This can be used to check if groups are selected, by comparing the length of the results when groups are expanded and not expanded.

Parameters

Parameter Description
expandGroups (Optional) If set to true, group nodes will be expanded into their component nodes. Otherwise, nodes of type “GroupNode” will be included in the results.

getStrokeColour

var colour = ctx.getStrokeColour();

Returns the default outline colour for shapes drawn in the future. This value is set using setColour

getNodeUnderPoint

// get the id of the zwibbler node under coordinate 100, 100 in the web page
var documentPoint = ctx.getDocumentCoordinates(100, 100);
var node = ctx.getNodeUnderPoint(documentPoint.x, documentPoint.y);

Gets the id of the node under the point. The node must be in the active layer. If there is nothing under the point, then returns null. The point is in document coordinates. You can obtain document coordinates from a position on the web page using getDocumentCoordinates(x, y)

Parameters

Parameter Description
x The x coordinate relative to the drawing
y The y coordinate relative to the drawing

getViewRectangle

// scroll 100 document pixels to the left
var rect = ctx.getViewRectangle();
rect.x += 100;
ctx.setViewRectangle(rect);

Returns the rectangle in the document that is visible on screen. This takes into account any scrolling, panning, or zooming. You may, for example, call getViewRectangle, change the x, and y coordinates, and pass the result to setViewRectangle. To implement scrolling. This rectangle may be larger than the document size, and might contain negative coordinates.

insertPage

// insert a page before the current one.
var currentPageNumber = ctx.insertPage(ctx.getCurrentPage());

Inserts a page at the given index, which must be less than or equal to the page count. This function can be part of a transaction and can be undone. Returns the index passed in.

Parameters

Parameter Description
index The index at which you want to insert page.

isLayerVisible

if (ctx.isLayerVisible("default")) {
    // ...
}

Returns true if the layer of the given name has not been hidden by a call to showLayer.

Parameters

Parameter Description
layerName The name of the layer whose visibility you want to find.

See also

Protecting parts of the document with layers

load

var saved = ctx.save();

// later ...

ctx.load(saved);

Open the document from the specified string.

Parameters

Parameter Description
data The document that you want to load.

lockUpdates

// prevent the screen from refreshing.
ctx.lockUpdates(10);

// make many changes to the document

Suppress updates to the drawing for the given amount of time in milliseconds. This is useful when making many transactions at once, to prevent the screen from flickering during the updates.

Parameters

Parameter Description
timeout The number of milliseconds to suppress updates.

moveDown

$("#movedown-button").click(function() {
    ctx.moveDown();
})

Move the selection one layer down. See also sendToBack, bringToFront

moveUp

$("#moveup-button").click(function() {
    ctx.moveUp();
})

Move the selection one layer up. See also moveDown, sendToBack, bringToFront

newDocument

if (!ctx.dirty() || confirm("Do you want to discard your changes?")) {
    ctx.newDocument();
}

Immediately clears the document and starts with a blank one.

nextPage

ctx.nextPage();

Switch to the next page, if possible.

on

Calls the given function when the named event occurs.

Parameters

Parameter Description
eventName The name of the event. See Events
fn The Javascript function to call when the event occurs. The arguments to the function depend on the event type.

See Also

Events

onComplete

ctx.load(myDocumentFromServer);
ctx.onComplete(function() {
    // save to png
    var pngFile = ctx.save("png");
});

When all images in the document have finished loading and it has been formatted, call the given function once, then forget about it. If there is no formatting to be done, then the function is called after a call to the HTML setTimeout function with 0 ms. After calling it once, Zwibbler forgets about it, so if you need notification again, you must ask for notification again. For instance, you may ask for notification:

paste

var snippet = ObtainSavedSnippetFromDatabase();
ctx.paste(snippet);

If possible, paste from the Zwibbler clipboard into the document. If data is passed in, it is used instead of the Zwibbler clipboard.

Parameters

Parameter Description
data The data is a string returned from the copy function.

previousPage

ctx.previousPage();

If possible, switch to the previous page.

print

// print whole drawing
ctx.print();

// print only what is currently visible
 ctx.print(zwibbler.getCurrentPage(), zwibbler.getViewRectangle());

Cause the browser to print the document, optionally allowing you to specify pages and a partial rectangle.

Parameters

Parameter Description
pages “pages” can be null, for the whole document, a zero-based page number, to print a single page, or an array of numbers, to print specific pages.
rect “rect” is either null, to print the whole drawing, or an object with x, y, width, and height to print a specific area.

redo

ctx.redo();

If possible, redo an action that has been undone.

redraw

ctx.redraw(function(ctx) {
    // draw a square on top of the drawing
    ctx.fillStyle = "red";
    ctx.fillRect(10, 10, 100, 100);
});

Redraw the canvas and then call the given function, allowing you to perform further drawing on top of it. This is useful when creating a custom tool.

Parameters

Parameter Description
fn (Optional) The javascript function to call after drawing occurs. The function is called with the CanvasRenderingContext2D as its argument. The canvas has already been scaled and translated to take into account scrolling and zooming.

resize

var container = document.querySelector("#myzwibbler");
container.style.width = "800px";
container.style.height = "600px";
ctx.resize();

Trigger Zwibbler to resize itself to the size of its container. It should not be necessary to call this function, because Zwibbler automatically sizes itself when it receives the HTML5 window Resize event. However, it may be necessary if you change the container’s size through javascript.

save

$("#save-button").click(function() {
    var saved = ctx.save();
    // send saved document to database.
});

Returns a string with the document saved in the specified formats.

Parameters

Parameter Description
format Valid formats are: png, jpeg, bmp, svg, pdf, zwibbler3. Jpeg is not supported on some browsers. If jpeg is not supported, the browser may return a png file instead. This can be detected if it starts with “data:image/png;base64,”.
rect optional rectangle, with x, y, width, and height keys, that defines the region to export when saving as an image.

See also

the download function

sendToBack

ctx.sendToBack();

Move the selection to the back. See also moveDown, bringToFront

selectNodes

var nodes = ctx.findNodes("treasure-markers");
ctx.selectNodes(nodes);

Given an array of node ids, add them to the current selection.

Parameters

Parameter Description
nodes Array of node ids.You can also pass a single node id instead of an array.

setActiveLayer

// manually set a background image.
ctx.setActiveLayer("background");
ctx.createNode("ImageNode", function() {
    url: "background-image.png";
});
ctx.setActiveLAyer("default");

Sets the active layer in which new objects are created. The default layer is named “default”. If the given layer does not exist, it is created by this function.

Parameters

Parameter Description
layerName Name of the layer.

See also

Protecting parts of the document with layers

setConfig

ctx.setConfig("backgroundImage", "http://zwibbler.com/logo.png");

Sets the configuration option and immediately updates the display. The name is one of the configuration options for Zwibbler. The value must match the expected type of the configuration option. For example, if a boolean value is expected, it must be true or false. If it is a string, then it is converted to the proper type.

In this version, only some of the options will have an immediate effect. These include the default colours and some others. If you need to set an option with this method instead of when Zwibbler is created, and that option does not have an effect, then email support and it will be added for you.

If the value could not be set, then the function returns false and the reason is shown in the debug window.

Parameters

Parameter Description
name Name of the Option.
value Value of the option

See also

getConfig, Configuration Settings

setColour

// red with a black outline.
ctx.setColour("red", true);
ctx.setColour("black", false);

Simulates the user clicking on a colour in the colour panel. This might colour the current shape or set the brush colour, depending on the tool that is selected.

Parameters

Parameter Description
colour Colour.
useFill “useFill” indicates whether the colour should affect the fill or outline colour.

See also

setOpacity

setCurrentPage

ctx.setCurrentPage(0);

Switch to the given page, given its zero-based page number. If this is called within a transaction, then the set-page event is not emitted.

Parameters

Parameter Description
index The index of the page, we want to switch to.

setCursor

ctx.setCursor("pointer");

Sets the CSS cursor of the canvas. This can be useful when creating a custom tool.

Parameters

Parameter Description
cursor The CSS cursor property to use.

setDomNode

ctx.on("convert-dom-request", function(id, dataString) {
    var element = document.createElement("h1");
    element.innerHTML = dataString;
    ctx.setDomNode(id, element);
});

When there are HTML DOM nodes in the drawing, that you have created using the createNode function, Zwibbler will send the convert-dom-request event to ask for you to convert their data property into an HTML element. Use this function to render the newly created HTML element in the drawing.

Parameters

Parameter Description
id The id of the zwibbler node to modify
element The newly created HTML element to place into the Zwibbler drawing.

See also

Including DOM Elements in the drawing

setDocumentSize

// set an 800x600 document size and show the visible page area.
ctx.setConfig("pageView", true);
ctx.setDocumentSize(800, 600);

Sets the document size. When the viewing area is larger than this size, then scrollbars will appear. If the document size is never set, or you set the width and height to null, then the size will always be calculated based on the content.

Use setDocumentSize(null, null) to remove a previously set document size.

The user will not be able to undo this. Use setDocumentSizeInTransaction instead to allow the user to undo the action.

Parameters

Parameter Description
width The new width of the document.
height The new height of the document.

setDocumentSizeInTransaction

The user undoable version of setDocumentSize.

setLayerName

ctx.setLayerName("student-1", "student-2");

Renames the layer.

Parameters

Parameter Description
oldName The old name for the layer.
newName The new name for the layer.

setPaperSize

ctx.setPaperSize("letter", false);

Sets the current paper size. You can specify a width and height in 96 dpi units.

Parameters

Parameter Description
name Paper sizes. Valid paper sizes are letter, legal, tabloid, 11x17, A0, A1, A2, A3, A4.
landscape (optional) Set true for landscape mode, false for portrait mode.

or

Parameter Description
height height of paper in 96 dpi units.
width width of paper in 96 dpi units.

setNodeProperty

ctx.setNodeProperty(ctx.getSelectedNodes(), "fillStyle", "red");

Sets the property of the specified node.

Parameters

Parameter Description
id The ID of the node, or an array of ids.
property The property of the node that we want to set.
value The value for the property.

See also

Node properties

setNodeProperties

ctx.setNodeProperties(ctx.getSelectedNodes(), {
    fillStyle: "red",
    lineWidth: 4,
    strokeStyle: "black"
});

Sets multiple properties of the given node. The properties parameter is an object containing the property values.

Parameters

Parameter Description
id The ID of the node.
properties The property of the node that we want to set.

See also

setToolProperty, getPropertySummary

setNodeVisibility

ctx.setNodeVisibility(ctx.findNodes("treasure-markers"), false);

Sets whether the node is visible or not. Nodes that are invisible cannot be clicked on and are not drawn. This property is not saved with the document.

Parameters

Parameter Description
id The id parameter may be a number or an array.
isVisible Set as true or false to display or hide the node.

setOpacity

// make the fill colour partially transparent
ctx.setOpacity(0.5, true);

// make the outline colour fully opaque
ctx.setOpacity(1.0, false);

Modifies the opacity of the fill or stroke colour of the selected shapes, if any, and sets the default to be used in the future.

Parameter Description
opacity A number between 0.0 and 1.0, with 1.0 being fully opaque.
useFill If true, the fill colour will be affected. Otherwise, the outline colour will be affected.

See also

setColour

setToolProperty

ctx.setToolProperty("fillStyle", "red");

Sets the property of the shape that is about to be drawn. The property change only applies until the current tool changes.

Parameter Description
property The property of the node that we want to set.
value The value for the property.

See also

setNodeProperties, getPropertySummary

showLayer

ctx.showLayer("student", true);
ctx.showLayer("teacher", false);

Sets whether the given layer is visible.

Parameters

Parameter Description
layerName The name of the layer.
shown Set as true or false to display or hide the layer.

See also

Protecting parts of the document with layers

setViewRectangle

// scroll 100 document pixels to the left
var rect = ctx.getViewRectangle();
rect.x += 100;
ctx.setViewRectangle(rect);

Sets the position and scale at once, so that the viewing area exactly contains the given rectangle. The rectangle is the same format as returned by getViewRectangle.

Parameters

Parameter Description
rectangle This rectangle must be an object that contains x, y, width, and height properties. All other properties are ignored. width and height must be non-zero. The coordinates are relative to the document, in 96 dpi units.

setZoom

ctx.setZoom(0.5);

Scales the view to the given scale.

Parameters

Parameter Description
option This option should be a number or “width” or “page”.

translateNode

// move selection 100 pixels to the right
ctx.translateNode(ctx.getSelectedNodes(), 100, 0);

Moves the given node(s) by the x, y amount. This can be part of a transaction.

Parameters

Parameter Description
id The single node or an array of nodes.
x The amount you want to move the node in x coordinate.
y The amount you want to move the node in y coordinate.

rotateDocument

// rotate document 90 degrees clockwise.
ctx.rotateDocument(Math.PI / 2);

// rotate the document. The user will not be able to undo.
ctx.beginTransaction();
ctx.rotateDocument(Math.PI / 2);
ctx.commitIrreversibleTransaction();

Rotates the entire document by the angle in radians. The document size may automatically changed by this function. This action can be undone by the user.

Parameters

Parameter Description
angle The angle in radians. The angle must be a multiple of PI/2 (90 degrees).

rotateNode

// Rotate selection by 60 degrees clockwise
ctx.rotateNode(ctx.getSelectedNodes(), 60 / 180 * Math.PI);

Rotates the given node by the angle in radians, around the optional x, y coordinates. If x and y are omitted, the node’s centre is used. This can be part of a transaction.

Parameters

Parameter Description
id The single node or an array of nodes.
angle The angle in radians.
x (optional) The x coordinate of the centre of rotation.
y (optional) The y coordinate of the centre of rotation.

scaleNode

// reduce the size of the selection by 50%
ctx.scaleNode(ctx.getSelectedNodes(), 0.5, 0.5);

Scale the given node by the x, y amount. This can be part of a transaction. The scaling is done relative to the optional origin ox,oy. If the origin is not specified, the centre of the node or nodes is used.

Parameters

Parameter Description
id The single node or an array of nodes.
sx The amount you want to scale the node in x coordinate.
sy The amount you want to scale the node in y coordinate.
ox The x coordinate of the centre of scaling
oy The y coordinate of the centre of scaling.

setNodeTransform

// remove all translation, scaling, and rotation from the selection
ctx.setNodeTransform(cx.getSelectedNodes(), 1, 0, 0, 1, 0, 0);

Clear the transformations for the node and set them to the given matrix.

Parameters

Parameter Description
id The single node or an array of nodes.
a, b, c, d, e, f The rows of the matrix are [a, c, e] [ b, d, f] [0, 0, 1]

undo

ctx.undo();

If possible, undo the last action.

ungroup

ctx.ungroup(ctx.getSelectedNodes());

If any of the nodes in the array are groups, then the group is split up into its members and removed. The group’s members remain in the document. Any nodes that are not groups are unaffected.

Parameters

Parameter Description
ids The single node or an array of nodes.

upload

  var form = document.getElementById("#file-upload-form");
    zwibbler.upload(form).
        success(function(response, xhr) {
            // response is the response from the server.
            // xhr is the XMLHttpRequest object.

            // Obtain the url to the image from the response
            // somehow

            // Insert the image into the document.
            ctx.beginTransaction();
            var nodeId = ctx.createNode("ImageNode", {
                url: url
            });
            ctx.translateNode(nodeId, 100, 100);
            ctx.commitTransaction();
        }.
        error(function(xhr) {
            // an error occurred or the request was aborted.
        });

Form is an HTML form element. This convenience function will upload the form to the server, and show appropriate progress notifications to the user. It is useful for uploading an image for use in the document.

Parameters

Parameter Description
form The HTML form element.

Return value

This returns an object that you can use to perform further actions upon success or when an error occurs.

useArrowTool

ctx.useArrowTool({
    arrowStyle: "solid",
    doubleArrow: true
});

Activates the arrow tool, as if the user clicked it on the toolbar.

Parameters

Parameter Description
properties The properties for Arrow tool. Additional properties can be given. For example, {arrowStyle: “solid”}
singleLine (optional) If singleLine is set to true, then only allow drawing one straight line. Otherwise, multiple line segments are allowed in the arrow.

useBrushTool

ctx.useBrushTool({
    lineWidth: 10, // optional
});

// eraser
ctx.useBrushTool({
    lineWidth: 10, // optional
    strokeStyle: "erase"
});

Activates the brush tool, as if the user clicked it on the toolbar. You may set the strokeStyle property to “erase” to implement an eraser tool.

Parameters

Parameter Description
properties Optional dictionary of properties that will override the default values.

useCircleTool

ctx.useCircleTool();

Activates the circle tool, as if the user clicked it on the toolbar.

Parameters

Parameter Description
properties Optional dictionary of properties that will override the default values.

useCurveTool

ctx.useCurveTool();

Activates the curve tool, as if the user clicked it on the toolbar.

Parameters

Parameter Description
properties The optional properties mapping is used to override the properties of the PathNode

useCustomTool

Activates a custom tool that you have defined. Create an object that implements the onMouseUp/Down/Move to customize the behaviour.

Parameters

Parameter Description
object The object instance of the tool you have defined.

See Also

Creating a custom tool

useEditHandleTool

var selection = ctx.getSelectedNodes();
if (selection.length) {
    <ctx class="useEditHandle"></ctx>Tool(selection[0]);
}

Begin editing the shape, given its node id. This is equivalent to clicking a shape and then clicking again, to enable its edit mode. Edit mode on a shape allows you to move its points, and an image allows you to crop it. You may call this on a node that is not in the active layer, and that is useful for allowing users to crop a background image.

Parameters

Parameter Description
nodeID The id of the node, we want to edit.

useFreehandTool

ctx.useFreehandTool({
    lineWidth: 5,
}, "freehand");

The freehand tool lets the user create smoothed brush strokes. The mode parameter determines how the curve is derived from the user’s movements.

Parameters

Parameter Description
properties The properties of the shape to be drawn, if you are overriding the defaults.
mode The type of processing to perform on the points.

Freehand modes

Mode Description
freehand (Default) The curve is smoothed.

useLineTool

ctx.useLineTool({
    lineWidth: 5
}, {
    singleLine: true
});

Activates the line tool, as if the user clicked it on the toolbar.

Parameters

Parameter Description
properties (optional) The line tool takes an optional object containing properties that let you control how the line looks, overriding the user’s default properties for line style, thickness, etc.
options (optional) An object altering the behaviour of the tool. When the “singleLine” member is set to true, then only allow drawing one line segment. Otherwise, it is possible to draw open and closed polygons. When the “orthogonal” member is set to true, only horizontal, vertical, or diagonal lines are allowed.

See Node Properties for a complete list of properties.

usePanTool

ctx.usePanTool();

Activates the pan tool, as if the user clicked it on the toolbar. The pan tool allows the user to drag the viewing area instead of using the scrollbars.

usePickTool

ctx.usePickTool();

Activates the pick tool, as if the user clicked it on the toolbar. The pick tool allows selecting shapes.

See also

The autoPickTool setting

usePolygonTool

// Let the user draw a triangle pointing up
ctx.usePolygonTool(3, 0);

// Let the user draw a triangle pointing to the right
ctx.usePolygonTool(3, Math.PI/2);

// Let the user draw a five-pointed star
ctx.usePolygonTool(10, 0, 0.5);

Activates the polygon tool. The user can draw a polygon with the given number of sides and rotation. The first vertex is placed at the top centre of the shape, unless a rotation is given.

Parameters

Parameter Description
numSides The number of sides for the polygon.
rotation The polygon is rotated by the given amount in radians.
innerScale (Default: 1.0) A number between 0.0 and 1.0. The radius of every odd vertex is multiplied by this amount, allowing you to create a star shape.

useQuadraticBezierTool

ctx.useQuadraticBezierTool();

Activates the quadratic Bezier tool, as if the user clicked it on the toolbar. A quadratic Bezier is a smooth curve having exactly one bend in it. This tool lets the user draw and edit a smooth curve.

Parameters

Parameter Description
properties Optional dictionary of properties that will override the default values.

useRectangleTool

ctx.useRectangleTool();

Activates the square tool, as if the user clicked it on the toolbar.

Parameter Description
properties The optional properties mapping is used to override the default properties.

useRoundRectTool

ctx.useRoundRectTool({
    roundRadius: 10
});

Activates the rounded rectangle tool.

Parameters

Parameter Description
properties The optional properties mapping is used to override the default properties.

useShapeBrushTool

ctx.useShapeBrushTool();

Activates the Shape Brush tool, as if the user clicked it on the toolbar. The shape brush allows the user to draw a crude shape. When they release the mouse, it will be changed into the closest perfect polygon with straight edges, as a PathNode.

Parameters

Parameter Description
properties The optional properties mapping is used to override the default properties for the PathNode.

useStampTool

ctx.useStampTool("stamp-image.png");

// Alternatively, specify properties to prevent resizing and also allow only
// one copy before returning to the Pick tool.
ctx.useStampTool({
    url: "stamp-image.png",
    lockSize: true
}, false);

Activates the stamp tool. The stamp tool allows the user to place an image multiple times by clicking.

Parameters

Parameter Description
url As a string, this is the URL of the image. Alternatively, you may pass an object containing the properties of the image. In this case, you must include the url property.
multiple (Default: true) When omitted or set to true, the user will be able to stamp multiple copies of the image. When explicitly set to false, the pick tool will be activated after one stamp.

useStampLineTool

ctx.useStampLineTool("ribbon.png");

Activates the stamp-line tool. The stamp-line tool allows the user to draw a line. However, instead of a solid colour, the line is drawn by laying copies of the given image end to end.

Parameters

Parameter Description
url The url is the URL of the image.

useTextTool

ctx.useTextTool();

Activates the text tool, as if the user clicked it on the toolbar.

zoomIn

ctx.zoomIn();

Increase the scale by a preset amount (currently 1.1)

zoomOut

ctx.zoomOut();

Decrease the scale by a preset amount (currently 1/1.1)

Internal Architecture

Licensed users get access to the source code, and the ability to modify it. Here is some information that will help a developer navigate the source code.

The Zwibbler name space

When the Zwibbler script is included in a web page, it will create the Zwibbler name space. The Zwibbler name space contains the create() function, to create instances of the drawing application, and also includes the ability to extend the functionality of Zwibbler. The Zwibbler name space is the only global variable created. All other variables are hidden inside of a javascript (function(){}()) closure. This avoids interfering with other libraries that you may be using.

The Application Object

The Application class creates and holds references to all of the other objects. It fills the <div> container that you give it with the toolbar, colour palette, and an HTML5 Canvas drawing area. When the <div> element is resized, it takes care of positioning all of the controls inside of it.

The ZwibblerCanvas

The ZwibblerCanvas manages interaction with the canvas drawing area. For example, it registers for pointer and touch events, and forwards them to the current behaviour. Several different behaviours exist, depending on the tool that is currently active. For example, the DefaultBehaviour implements the mouse click event by selecting the shape that is under the mouse. The DrawLines behaviour responds to a click by adding a point to the path that the user is drawing.

The ZwibblerCanvas is responsible for the following major functions:

The ZwibblerDocument

The ZwibblerDocument contains a tree of nodes that represent the document. These nodes are an internal representation of the drawing. They are not DOM elements. Here is an example document.

Zwibbler document structure

Nodes can have children. Nodes can be configured with different properties. For example, the PathNode has a property for the fillStyle, lineWidth, strokeStyle, and text. In the example above, the paths would have a “path” property that has a list of points through which the path flows. The BrushNode would have a list of points, a lineWidth, and a fillStyle. All nodes are required to have a 2-D transformation matrix that tells how to draw them.

There are several types of nodes that could be in the document:

Node Name Node Description
RootNode The root is a group node that contains all the other nodes.
GroupNode A group node can contain other nodes. The nodes are selected as if they were one, and move as a group. It is not drawn, and its transformation matrix is ignored.
PathNode The path node is a very complex node. It contains code and logic that will draw arbitrary lines or shapes. Paths can be closed or open. For example, an open path is a line, curve, or can have an arrow head. A closed path can have a fill colour or contain text. The path node is used to implement squares, circles, lines, curves, and arrows.
BrushNode The brush node is a simpler path. It has a series of points and is drawn as a series of line segments.
ImageNode An image node can contain an image. Due to browser security restrictions, the URL of the image must come from the same server as the zwibbler script file.

Among others, Nodes of the document may implement two important functions:

Function Name Function Description
format Calculates the bounding rectangle of the node, and any other data that is required to quickly draw it to the screen. format() is guaranteed to be called whenever one or more properties change, before drawing.
draw draw the node to the given Canvas drawing context. The drawing context has already been transformed to take into account any movement, rotation, or stretching of the node by the user.

Data Storage

Zwibbler application can save data in two different formats:

Zwibbler can only open a document in the “zwibbler3” format. It cannot open a document from a PNG file, although a PNG file can be inserted into a new document as an ImageNode.

Here is a short description of the file format used by Zwibbler. The file format consists of the string “zwibbler3.” Followed by a JSON array. Each array element is a JSON object, with keys and values equal to the properties of the node. Properties whose value is a transformation matrix receive special handling. The matrix of the form

is stored as an array [a, b, c, d, x, y].

In addition, the object has three additional members:

Path Commands

/** @constructor 
    @param {Array.=} commands

    Path commands are an array of commands for drawing shapes. Each command
    other than CLOSE_SHAPE has the command type and the final x and y
    coordinates. Depending on the command type, there may be other coordinates.
 */
function PathCommands(commands)
{
    this.init(commands);
}

PathCommands.prototype = {
    init: function(commands)
    {
        if ( commands === undefined ) {
            this.commands = [];
        } else {
            this.commands = commands;
        }
    },

    moveTo: function( x, y )
    {
        this.commands.push( 0 );
        this.commands.push( x );
        this.commands.push( y );
    },

    lineTo: function( x, y )
    {
        this.commands.push( 1 );
        this.commands.push( x );
        this.commands.push( y );
    },

    curveTo: function( x, y )
    {
        this.commands.push( 5 );
        this.commands.push( x );
        this.commands.push( y );
    },

    quadraticTo: function( cx, cy, x, y )
    {
        this.commands.push( 2 );
        this.commands.push( x );
        this.commands.push( y );
        this.commands.push( cx );
        this.commands.push( cy );
    },

    cornerTo: function( cx, cy, x, y )
    {
        this.commands.push( 6 );
        this.commands.push( x );
        this.commands.push( y );
        this.commands.push( cx );
        this.commands.push( cy );
    },

    bezierTo: function( c1x, c1y, c2x, c2y, x, y )
    {
        this.commands.push( 4 );
        this.commands.push( x );
        this.commands.push( y );
        this.commands.push( c1x );
        this.commands.push( c1y );
        this.commands.push( c2x );
        this.commands.push( c2y );
    },

    arcTo: function( x1, y1, x2, y2, radius )
    {
        this.commands.push( 3 );
        this.commands.push( x2 );
        this.commands.push( y2 );
        this.commands.push( x1 );
        this.commands.push( y1 );
        this.commands.push( radius );
    },

    closePath: function()
    {
        this.commands.push( 7 );
    },

    toArray: function()
    {
        return this.commands;
    }
};

function CreateCirclePath( centre, radius )
{
    var commands = new PathCommands();
    commands.moveTo( centre.x, centre.y - radius );
    commands.cornerTo( centre.x + radius, centre.y - radius, 
                          centre.x + radius, centre.y );
    commands.cornerTo( centre.x + radius, centre.y + radius, 
                          centre.x, centre.y + radius );
    commands.cornerTo( centre.x - radius, centre.y + radius, 
                          centre.x - radius, centre.y);
    commands.cornerTo( centre.x - radius, centre.y - radius, 
                          centre.x, centre.y - radius );
    commands.closePath();

    return commands.toArray();
}

var circle = zwibbler.createNode("PathNode",{ 
    commands: CreateCirclePath({x: 100, y: 100}, 50), 
    fillStyle: "#880000", 
    strokeStyle: "#000000",
    linewidth:20
});

A path is defined by an array of numbers. Each segment of the path is prefixed by a number from 0 to 8 describing the kind of command it is. The rest of the command is parameters pertaining to the command.

Change History

August 2017 - October 2017

May - July 2017

January - April 2017

October - December 2016

July - September 2016

April - June 2016

January - March 2016

December 2015

November 2015

October 2015

September 2015

August 2015

July 2015

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

December 2014

November 2014

October 2014

September 2014

August 2014

July 2014

Support

Support will normally be given by email for a minimum of one year from the date of purchase. Email steve.hanov@gmail.com.