Project
A Project object in Paper.js is what usually is referred to as the document: The top level object that holds all the items contained in the scene graph. As the term document is already taken in the browser context, it is called Project.
Projects allow the manipulation of the styles that are applied to all newly created items, give access to the selected items, and will in future versions offer ways to query for items in the scene graph defining specific requirements, and means to persist and load from different formats, such as SVG and PDF.
The currently active project can be accessed through the paperScope.project variable.
An array of all open projects is accessible through the paperScope.projects variable.
Constructors
Creates a Paper.js project containing one empty Layer, referenced by project.activeLayer.
Note that when working with PaperScript, a project is automatically created for us and the paperScope.project variable points to it.
- element: HTMLCanvasElement⟋String⟋Size — the HTML canvas element that should be used as the element for the view, or an ID string by which to find the element, or the size of the canvas to be created for usage in a web worker.
Parameters:
- Project
Returns:
Properties
The style new text items take in a hosted project, in place of currentStyle, when the host sets one: for hosts whose new text has defaults of its own, such as a black fill without a stroke whatever new paths take. Paths keep taking the current style.
- Style
Type:
The host document that the project’s items come from. Setting it creates the project’s layers from the host’s records. All items are created as shells that load their content and children from the host on first access. The host draws its items, so setting it also turns off view.autoUpdate, which would draw them all and load them in full.
The host provides: - getChildren(key), which returns the records of the children of the node with the given key, or of the top level for null, as columns: keys, types (indices into typeNames), typeNames, flags (selected: 1, visible: 2, locked: 4, strokeScaling: 8, clipMask: 64, guide: 128, empty: 256), optionally boxes (bounds, strokeBounds and roughBounds in the item’s coordinates, 12 numbers per item), and the sparse objects names and matrices. - getBounds(key), for hosts that don’t send boxes, which returns the node’s 12 numbers, or null for an empty node. Items ask for them when their bounds are needed, and again after the host sent their record again. - getItem(key), which returns the node’s own content in the form of item.importJSON(json), without children. Linked text gives linked, the keys of its story’s text items in order, and leaves out its story. Rasters give their size without a source and crossOrigin. - getImage(key), for rasters, which returns the node’s pixels as a canvas with a 2D context, of the size that getItem() gives. Rasters load them on first access to their pixels, and Paper.js never loads them by itself, except to draw them. Rasters whose pixels the host fails to give draw nothing. - getStory(key), for linked text, which returns its story with the key of any of its text items: content or runs, paragraphs, and the character and paragraph styles, as item.exportJSON(options) writes them in the JSON of a text item. - getAncestorKeys(key), which returns the keys from the top level down to the node’s parent. - Optionally layOut(json, start, key), which lays out a text item from start in its story, given as the JSON string that item.exportJSON(options) writes of it as the script holds it, or as null where the script didn’t change it since it loaded or the host took its changes with project.takeChanges(), for the host to lay out its own node, and returns { end, lines }: where its visible text ends, and its lines, each { start, end, x, y, width, lineHeight, ascent,
descent, pieces }, with pieces { start, end, x, y, dx, width,
rotation, size, ascent, descent, lineHeight } and an optional content, as for a hyphen, all in the item’s coordinates. key is null for text that the host doesn’t know yet. Without it, Paper.js lays out text itself. - getDefinition(key), for the pattern and symbol definitions that the host shares between its items, which the JSON of its items refers to as ['@key'], as in fillColor: ['pattern',
['@pattern/Dots'], matrix] or definition: ['@symbol/Star']. It returns the definition in the form of item.exportJSON(options), with its whole item: ['PatternDefinition', item, { tile, spacing }] or ['SymbolDefinition', item], always: for a key that it has no definition of, an empty one of the type, as ['SymbolDefinition', ['Group', {}]]. Each definition loads once, and the JSON of the items that use it, as item.exportJSON(options) writes it, refers to it by its key again. Definitions that scripts create have no key, and are written out whole, until the host sets their key, which it can only set once. project.takeChanges() lists those that the changed items use first, nested ones first, as { definition, flags } with the ChangeFlag.INSERTION flag, followed by the changes of the host’s definitions. Renaming those isn’t supported. - getDefinitionKeys(type), which returns the keys of all the host’s definitions of the type, 'SymbolDefinition' or 'PatternDefinition', for symbolDefinitions and patternDefinitions.
Items that move into a project with another host load in full from their own host first, and drop their keys, so they are new items there. They bring copies without keys of the symbol and pattern definitions of their host along, shared by the items of one insertion or copy, so the new host takes them as new ones too. Linked text brings a copy of its story along, which flows on through the items that stay. Host items can’t enter the project of another host.
The host draws the items, and the selection. To show what scripts draw in item.onDraw and item.onDrawSelection, it calls project.draw(ctx, matrix, pixelRatio), which in a hosted project only calls these handlers, with the context, the view’s matrix and pixel ratio that the host gives, for the visible items that have them, and for the selected ones. Handlers of classes, such as Path.onDraw, load all items once. The host asks hasDrawHandlers() whether it needs to call it.
project.takeChanges() marks the changes of the items whose children changed in order other than by new items inserted and items removed, which the other changes don’t tell, with reordered: true: the host reads their children whole, and can place the others’ new items by their indices.
- Object
Type:
Specifies whether the project logs the changes of its items, to be retrieved through takeChanges(). This allows hosts that keep their own document to update only what has changed.
- false
Default:
- Boolean
Type:
The function to be called when the project is activated through activate(). The function receives the previously active project, which is the project itself when it was already active.
- Function⟋null
Type:
The function to be called when another project is activated through activate() while this one is active, or when this one is removed while active.
- Function⟋null
Type:
The currently active path style. All selected items and newly created items will be styled with this style.
- Style
Type:
Example:
Example:
Project Content
The layer which is currently active. New items will be created on this layer by default.
Read only.
- Layer
Type:
The symbol definitions shared by all symbol items contained place ind project.
Read only.
- Array of SymbolDefinition objects
Type:
The pattern definitions that the fill and stroke colors of the items in the project use.
Read only.
- Array of PatternDefinition objects
Type:
Static Properties
The function to be called when any project is activated, as onActivate is for a single project, including the projects that activate themselves when they are created, with this set to the project. Project.on('activate', handler) and Project.off('activate', handler) attach and detach them too. Classes are shared by all PaperScope objects, and so are their handlers.
- Function⟋null
Type:
The function to be called when any project is deactivated, as onDeactivate is for a single project, see Project.onActivate.
- Function⟋null
Type:
Methods
Returns the item of the host’s node with the given key, loading only the children of its ancestors.
- key: Number — the key of the host’s node
Parameters:
-
Item — the item, or
nullif the host has no such node
Returns:
Checks whether any item of the project or class has draw handlers, item.onDraw or, for the selected items, item.onDrawSelection, for hosts that draw the items themselves, see host.
- Boolean — true if drawing the project calls any handlers, false otherwise
Returns:
Updates the items of changed host nodes, given in the column format of the host’s getChildren(), with two more flags: 16 when the node’s own content changed, so the item loads it again on next access, and 32 when its list of children changed, so it loads them again right away if it had loaded them, keeping the items of nodes that remain. Nodes without items are skipped. definitions lists the keys of changed definitions of the host’s getDefinition(), which load again right away into the same objects, so the colors and symbol items that use them change along. A definition that the host no longer has, for which getDefinition() may return null here, is emptied and draws nothing. The columns may hold only definitions.
- columns: Object — the records of the changed nodes
Parameters:
Returns the changes logged since tracking was activated or since the last call, and clears the log. Each item is listed once, with the ChangeFlag values of all its changes combined. Removed items are listed with the ChangeFlag.INSERTION flag, and items that moved to another project are left out, as that one lists them. Symbol and pattern definitions whose item, tile, spacing or name changed are listed too, as { definition, flags }.
-
Array of Object objects — the changes as
{ item, flags }and{ definition, flags }objects, ornullif trackChanges is off
Returns:
Checks whether changes were logged since tracking was activated or since the last call of takeChanges(), without taking them.
- Boolean — true if changes were logged, false otherwise
Returns:
Activates this project, so all newly created items will be placed in it.
Clears the project by removing all project.layers.
Checks whether the project has any content or not.
- Boolean
Returns:
Removes this project from the paperScope.projects list, and also removes its view, if one was defined.
Selects all items in the project.
Deselects all selected items in the project.
Hierarchy Operations
Hit-testing, Fetching and Matching Items
Performs a hit-test on the items contained within the project at the location of the specified point.
The options object allows you to control the specifics of the hit-test. Without options, fill, stroke and segments are hit-tested. As soon as an options object is passed, only the hit-tests that it sets to true are performed. It may contain a combination of the following values:
- options.tolerance: Number — the tolerance of the hit-test, in project coordinates — default: paperScope.settings.hitTolerance
- options.class: Function — only hit-test against a specific item class, or any of its sub-classes, by providing the constructor function against which an
instanceofcheck is performed: Group, Layer, Path, CompoundPath, Shape, Raster, SymbolItem, PointText, … - options.match: Function — a match function to be called for each found hit result: Return
trueto return the result,falseto keep searching - options.fill: Boolean — hit-test the fill of items
- options.stroke: Boolean — hit-test the stroke of path items, taking into account the setting of stroke color and width
- options.segments: Boolean — hit-test for segment.point of Path items
- options.curves: Boolean — hit-test the curves of path items, without taking the stroke color or width into account
- options.handles: Boolean — hit-test for the handles (segment.handleIn / segment.handleOut) of path segments.
- options.ends: Boolean — only hit-test for the first or last segment points of open path items
- options.position: Boolean — hit-test the item.position of of items, which depends on the setting of item.pivot
- options.center: Boolean — hit-test the rectangle.center of the bounding rectangle of items (item.bounds)
- options.bounds: Boolean — hit-test the corners and side-centers of the bounding rectangle of items (item.bounds)
- options.guides: Boolean — only hit-test items that have item.guide set to
true - options.selected: Boolean — only hit selected items
Options:
- point: Point — the point where the hit-test should be performed
- options: Object — optional, default: { fill: true, stroke: true, segments: true, tolerance: settings.hitTolerance }
Parameters:
-
HitResult — a hit result object that contains more information about what exactly was hit or
nullif nothing was hit
Returns:
Performs a hit-test on the item and its children (if it is a Group or Layer) at the location of the specified point, returning all found hits.
The options object allows you to control the specifics of the hit- test. See hitTest(point[, options]) for a list of all options.
- point: Point — the point where the hit-test should be performed
- options: Object — optional, default: { fill: true, stroke: true, segments: true, tolerance: settings.hitTolerance }
Parameters:
-
Array of HitResult objects — hit result objects for all hits, describing what exactly was hit or
nullif nothing was hit
Returns:
- hitTest(point[, options]);
See also:
Fetch items contained within the project whose properties match the criteria in the specified object.
Extended matching of properties is possible by providing a comparator function or regular expression. Matching points, colors only work as a comparison of the full object, not partial matching (e.g. only providing the x- coordinate to match all points with that x-value). Partial matching does work for item.data.
Matching items against a rectangular area is also possible, by setting either options.inside or options.overlapping to a rectangle describing the area in which the items either have to be fully or partly contained.
- options.recursive: Boolean — whether to loop recursively through all children, or stop at the current level — default: true
- options.match: Function — a match function to be called for each item, allowing the definition of more flexible item checks that are not bound to properties. If no other match properties are defined, this function can also be passed instead of the
matchobject - options.class: Function — the constructor function of the item type to match against
- options.inside: Rectangle — the rectangle in which the items need to be fully contained
- options.overlapping: Rectangle — the rectangle with which the items need to at least partly overlap
Options:
- options: Object⟋Function — the criteria to match against
Parameters:
- Array of Item objects — the list of matching items contained in the project, in their stacking order from bottom to top, with each item listed before its own descendants
Returns:
- item.matches(options)
- item.getItems(options)
See also:
Example:Fetch all selected path items:
Example:Fetch all items with a specific fill color:
Example:Fetch items at a specific position:
Example:Fetch items using a comparator function:
Example:Fetch items using a comparator function (2):
Example:Match (nested) properties of the data property:
Example:Match strings using regular expressions:
Fetch the first item contained within the project whose properties match the criteria in the specified object. Extended matching is possible by providing a compare function or regular expression. Matching points, colors only work as a comparison of the full object, not partial matching (e.g. only providing the x- coordinate to match all points with that x-value). Partial matching does work for item.data.
See getItems(options) for a selection of illustrated examples.
- options: Object⟋Function — the criteria to match against
Parameters:
- Item — the first item in the project matching the given criteria
Returns:
Importing / Exporting JSON and SVG
Exports (serializes) the project with all its layers and child items to a JSON data object or string.
- options.asString: Boolean — whether the JSON is returned as a
Objector aString— default: true - options.precision: Number — the amount of fractional digits in numbers used in JSON data — default: 5
Options:
- options: Object — the serialization options — optional
Parameters:
- String — the exported JSON data
Returns:
Imports (deserializes) the stored JSON data into the project. Note that the project is not cleared first. You can call project.clear() to do so.
- json: String — the JSON data to import from
Parameters:
- Item — the imported item
Returns:
Exports the project with all its layers and child items as an SVG DOM, all contained in one top level SVG group node.
- options.bounds: String⟋Rectangle — the bounds of the area to export, either as a string (‘view’, content’), or a Rectangle object:
'view'uses the view bounds,'content'uses the stroke bounds of all content — default: ‘view’ - options.matrix: Matrix — the matrix with which to transform the exported content: If
options.boundsis set to'view',paper.view.matrixis used, for all other settings ofoptions.boundsthe identity matrix is used. — default: paper.view.matrix - options.asString: Boolean — whether a SVG node or a
Stringis to be returned — default: false - options.precision: Number — the amount of fractional digits in numbers used in SVG data — default: 5
- options.matchShapes: Boolean — whether path items should tried to be converted to SVG shape items (rect, circle, ellipse, line, polyline, polygon), if their geometries match — default: false
- options.embedImages: Boolean — whether raster images should be embedded as base64 data inlined in the xlink:href attribute, or kept as a link to their external URL. — default: true
- options.reuseImages: Boolean — whether raster images with the same content should only be exported once into the
<defs>element, and placed through<use>elements referencing it — default: false - options.idPrefix: String — a prefix for the ids generated for definitions such as gradients, clip paths and symbols, to keep them unique when several exported SVGs are placed in one document — default: ’’
- options.reduceAttributes: Boolean — wether to only include style attributes in the SVG output that differ from their parents, or to always include them (much faster but leading to redundancies). — default: true
- [options.processNode] {Function} the function to process the SVG node made for each exported item, receiving an object with the `item` and its `node`: It can change the node, e.g. to add attributes that Paper.js doesn't export, or return a node to replace it with. It is called before the item's name, style, visibility and data are set on the node, which replace attributes of the same names.
Options:
- options: Object — the export options — optional
Parameters:
-
SVGElement⟋String — the project converted to an SVG node or a
Stringdepending onoption.asStringvalue
Returns:
Example:Export layers as Inkscape layers. Setting the attributes with their namespace has the exported SVG declare it:
var ns = 'http://www.inkscape.org/namespaces/inkscape';
var svg = project.exportSVG({
asString: true,
processNode: function(arg) {
var item = arg.item;
if (item instanceof Layer) {
arg.node.setAttributeNS(ns, 'inkscape:groupmode', 'layer');
if (item.name)
arg.node.setAttributeNS(ns, 'inkscape:label', item.name);
}
}
});
Converts the provided SVG content into Paper.js items and adds them to the active layer of this project. Note that the project is not cleared first. You can call project.clear() to do so.
<symbol> elements are imported as SymbolDefinition items, and the <use> elements that place them as SymbolItem items. The styles that <use> elements inherit don’t reach the symbols’ content.
The layers in SVG content that Paper.js exported come back as Layer items inside the imported group. To make the layers of a project’s SVG the layers of a project again, add them to it with item.children.slice().forEach(project.addLayer, project).
URLs are fetched as they are, so validate URLs that come from untrusted sources first, especially on servers, where they could reach internal addresses.
- options.expandShapes: Boolean — whether imported shape items should be expanded to path items — default: false
- [options.crossOrigin] {String} the {@link Raster#crossOrigin}
value of the rasters created for `
` elements, to load their images with CORS - options.onLoad: Function — the callback function to call once the SVG content is loaded from the given URL receiving two arguments: the converted
itemand the originalsvgdata as a string. Only required when loading from external resources. - options.onError: Function — the callback function to call if an error occurs during loading. Only required when loading from external resources.
- options.insert: Boolean — whether the imported items should be added to the project that
importSVG()is called on — default: true - options.applyMatrix: Boolean — whether the imported items should have their transformation matrices applied to their contents or not — default: paperScope.settings.applyMatrix
- [options.processItem] {Function} the function to process the item made for each imported SVG element, receiving an object with the `item` and its `node`: It can read attributes that Paper.js doesn't import, or return an item to replace it with. It is called after the element's attributes and data are applied to the item, so it can extend `item.data`. A replacement item doesn't receive them: copy them over from `item` as needed.
Options:
- svg: SVGElement⟋String — the SVG content to import, either as a SVG DOM node, a string containing SVG content, or a string describing the URL of the SVG file to fetch.
- options: Object — the import options — optional
Parameters:
- Item — the newly created Paper.js item containing the converted SVG content
Returns:
Example:Keep the SVG `class` attribute of items in their data, and export it again:
var item = project.importSVG(svg, {
processItem: function(arg) {
var className = arg.node.getAttribute('class');
if (className)
arg.item.data.className = className;
}
});
var exported = project.exportSVG({
processNode: function(arg) {
var className = arg.item.data.className;
if (className)
arg.node.setAttribute('class', className);
}
});
Imports the provided external SVG file, converts it into Paper.js items and adds them to the active layer of this project. Note that the project is not cleared first. You can call project.clear() to do so.
- svg: SVGElement⟋String — the URL of the SVG file to fetch.
-
onLoad:
Function
— the callback function to call once the SVG content is loaded from the given URL receiving two arguments: the converted
itemand the originalsvgdata as a string. Only required when loading from external files.
Parameters:
- Item — the newly created Paper.js item containing the converted SVG content