Cavalry 模組
Introduction
标题为“Introduction”的章节This module gives access to the Path class, functions for creating noise and random numbers along with a number of utilities to make working with color easier, and, a whole host of maths functions such as clamp, norm, map and dist. The following methods are available to the JavaScript Utility, and the JavaScript Editor. Everything in this module is in the cavalry namespace and so methods need prefixing with cavalry. e.g var distance = cavalry.dist(0,0,100,200);
The examples given are for use in the JavaScript Editor (less setup required to run examples).
JavaScript Deformers also have access to the def module, which provides methods for accessing and modifying the geometry being deformed.
Member Functions
标题为“Member Functions”的章节Path Class
标题为“Path Class”的章节The Cavalry module contains a Path class which can be used to construct paths which can then be drawn on screen. Path itself contains several methods.
Several of these methods use the word ‘param’ or ‘parameter’. This is a number between 0..1 which represents a progression along the curve’s control cage from 0 (the beginning) to 1 (the end). The control cage, formed by the curve’s control points, outlines the basic shape of the curve. Note that a ‘param’ value of 0.5 does not necessarily represent a position half way along the curve. This is because the relationship between the param value and the curve’s length is not linear due to the influence of the curve’s control points and its resulting shape. To convert length values into param values, use paramAtLength.
Right clicking on a Shape in the Viewport and choosing Copy as JavaScript will copy the Shape’s information to the clipboard as JavaScript code.
Drawing a path:
标题为“Drawing a path:”的章节var path = new cavalry.Path();path.moveTo(0.,0.);path.lineTo(0.,-100.);path.lineTo(300.,-100.);path.cubicTo(210., 110., 240., 140., 280., 260);path.close();path.translate(-300,-30);path.addText("hello world", 274, -700, 300);path.addRect(-300,-300,-200,-250);path.addEllipse(250, -300, 100,60);// this path can then be returned if on the JavaScript layer// or used to create an Editable Shape like soapi.createEditable(path, "My Path");moveTo(x:number, y:number)
标题为“moveTo(x:number, y:number)”的章节Start a new contour.
lineTo(x:number, y:number)
标题为“lineTo(x:number, y:number)”的章节Draw a line to x,y.
cubicTo(cp1X:number, cp1Y:number, cp2X:number, cp2Y:number, endX:number, endY:number)
标题为“cubicTo(cp1X:number, cp1Y:number, cp2X:number, cp2Y:number, endX:number, endY:number)”的章节Draw a cubic bezier with two control points and an end point.
quadTo(cp1X:number, cp1Y:number, endX:number, endY:number)
标题为“quadTo(cp1X:number, cp1Y:number, endX:number, endY:number)”的章节Add a quadratic bézier curve to the path.
arcTo(cp1X:number, cp1Y:number, cp2X:number, cp2Y:number, radius:number)
标题为“arcTo(cp1X:number, cp1Y:number, cp2X:number, cp2Y:number, radius:number)”的章节Draw an arc with two control points and a radius.
conicTo(cp1X:number, cp1Y:number, endX:number, endY:number, weight:number)
标题为“conicTo(cp1X:number, cp1Y:number, endX:number, endY:number, weight:number)”的章节Adds a conic to the path. Where weight:
= 1- the curve is a quadratic bézier curve (a conic with a weight of 1 is mathematically equivalent to a quadratic curve).< 1- the curve approximates an ellipse. The smaller the weight, the more the curve leans towards being circular, with smaller weights resulting in sharper curves.> 0- the curve begins to resemble a hyperbola. As the weight increases, the curve opens up more.= 0(or a very low value) - these may produce degenerate cases or curves that don’t visually change much from a straight line or a very sharp curve.
convertConicsToQuads()
标题为“convertConicsToQuads()”的章节Convert any conic verbs to quad verbs. This might be useful as not all features in Cavalry support conic verbs.
close()
标题为“close()”的章节Close the path.
addText(text:string, fontSize:int, positionX:number, positionY:number)
标题为“addText(text:string, fontSize:int, positionX:number, positionY:number)”的章节Add text to the path and position it. The text could be added to a separate path and then .append() it into this one if needed. The position arguments may be removed as a result of this.
var path = new cavalry.Path();path.addText("hello world", 274, -700, 300);api.createEditable(path, "My Path");addRect(fromX:number, fromY:number, toX:number, toY:number)
标题为“addRect(fromX:number, fromY:number, toX:number, toY:number)”的章节Convenience method for drawing a rectangle.
addEllipse(centreX:number, centreY:number, radiusX:number, radiusY:number)
标题为“addEllipse(centreX:number, centreY:number, radiusX:number, radiusY:number)”的章节Convenience method for drawing an ellipse.
clear()
标题为“clear()”的章节Empty the path.
isClosed → bool
标题为“isClosed → bool”的章节Returns a boolean signifying if the path is closed.
translate(x:number, y:number)
标题为“translate(x:number, y:number)”的章节Move the path by x and y.
rotate(degrees:number)
标题为“rotate(degrees:number)”的章节Rotate the path.
scale(x:number, y:number)
标题为“scale(x:number, y:number)”的章节Scale the path.
append(pathToAdd:path)
标题为“append(pathToAdd:path)”的章节Add one path to another.
intersect(intersectPath:path)
标题为“intersect(intersectPath:path)”的章节Perform a Boolean intersection.
unite(unitePath:path)
标题为“unite(unitePath:path)”的章节Perform a Boolean unite.
difference(differencePath:path)
标题为“difference(differencePath:path)”的章节Perform a Boolean difference.
The below example can be set on the JavaScript Shape.
function boolTest() { var mainPath = new cavalry.Path(); mainPath.addRect(-100,100,100,-100); var boolTest = new cavalry.Path(); boolTest.addEllipse(0,0,200,40); mainPath.difference(boolTest); return mainPath;}boolTest();convertToCurves()
标题为“convertToCurves()”的章节Resample lines as curves (the algorithm used by the Pencil Tool).
convertToLines(linesPerCurve:int)
标题为“convertToLines(linesPerCurve:int)”的章节Convert (vectorise) any curves into a series of lines.
toObject() → object
标题为“toObject() → object”的章节Converts the Path to an object that can be saved.
var path = new cavalry.Path();path.moveTo(0.,0.);path.lineTo(0.,-100.);path.lineTo(300.,-100.);// Convert to an Objectvar js = path.toObject();// Convert from a saved objectpath.fromObject(js);console.log(path.length);fromObject(objectToRead:object)
标题为“fromObject(objectToRead:object)”的章节Sets the path from an object.
var path = new cavalry.Path();path.moveTo(0.,0.);path.lineTo(0.,-100.);path.lineTo(300.,-100.);// Convert to an Objectvar js = path.toObject();// Convert from a saved objectpath.fromObject(js);console.log(path.length);back → {x:number, y:number}
标题为“back → {x:number, y:number}”的章节Return an object containing x and y keys describing the final point in a path.
var path = new cavalry.Path();path.addText("Cavalry", 30, 0, 10);console.log(JSON.stringify(path.back));boundingBox() → {x:number, y:number, width:number, height:number, centre:{x:number, y:number}, left:number, right:number, top:number, bottom:number}
标题为“boundingBox() → {x:number, y:number, width:number, height:number, centre:{x:number, y:number}, left:number, right:number, top:number, bottom:number}”的章节Return the bounding box of a path.
var path = new cavalry.Path();path.addText("Some text!", 22, 0, 10);var bbox = path.boundingBox();console.log(JSON.stringify(bbox));empty() → bool
标题为“empty() → bool”的章节Return if a path is empty or not.
pointCount() → int
标题为“pointCount() → int”的章节Return the number of points in the path.
contains(x:number, y:number) → bool
标题为“contains(x:number, y:number) → bool”的章节Return if the point specified by x,y is inside the path (only works on a closed path).
pathData() → object
标题为“pathData() → object”的章节This returns an array of dictionaries and provides a convenient way to iterate and change an existing path as opposed to creating a new Path Class. Each dictionary contains the verb type variable e.g. moveTo or lineTo along with any ‘point’ objects relevant to the verb.
The dictionary will contain different objects depending on the verb type:
moveTo: contains apointobject (with x and y variables).lineTo: contains apointobject (with x and y variables).quadTo: contains acp1object representing the control point (with x and y variables) along with apointobject (with x and y variables). This is the end point of thequadToverb.cubicTo: containscp1andcp2objects representing the first and second control points (both with x and y variables) along with apointobject (with x and y variables). This is the end point of thecubicToverb.close: contains no points.
setPathData(data:object)
标题为“setPathData(data:object)”的章节Set the path based on a pathData object.
offset(distance:number, round:bool)
标题为“offset(distance:number, round:bool)”的章节Grow or shrink a closed Path. The round argument determines whether the joins of the rebuilt Path’s line segments are rounded or not.
function getPath() { var path = new cavalry.Path() path.addRect(0, 0, 200, 200); path.offset(n0, true); return path;}getPath();trim(start:number, end:number, travel:number, reverse:bool)
标题为“trim(start:number, end:number, travel:number, reverse:bool)”的章节Reduce the length of a Path by clipping it from its start/end points.
function getPath() { var path = new cavalry.Path() path.addEllipse(0,0,200,200); path.trim(0.2, 0.5, 0.0, false); return path;}getPath();resample(edgeLength:number)
标题为“resample(edgeLength:number)”的章节Rebuilds the path by sampling points based on a desired ‘edgeLength’.
/*1. Create a Text Shape.2. Click the + button on the Text Shape's 'Deformers' attribute and choose 'JavaScript Deformer'.3. Paste the below into the JavaScript expression.*/var depth = 3;var frequency = 5;var multiplier = n0;var meshes = def.getMeshesAtDepth(depth);for (var mesh of meshes) { var path = mesh.getPathAtIndex(0); path.resample(5); var pd = path.pathData(); for (var idx = 0; idx < pd.length; idx++) { if (idx % frequency == 0) { let line = new cavalry.Line(0,0,pd[idx].point.x, pd[idx].point.y); line.setLength(line.length()+multiplier); pd[idx].point = line.end(); } } path.setPathData(pd); mesh.setPathAtIndex(0, path);}def.setMeshesAtDepth(depth, meshes);lineIntersections(line:cavalry.Line) → array[object]
标题为“lineIntersections(line:cavalry.Line) → array[object]”的章节Returns an array of points at which the path and line intersect.
/*1. Create 2 Nulls, an Ellipse and a JavaScript Shape.2. Right click the JavaScript Shape's n0 attribute and choose 'Delete Selected Attribute'.3. Use the + button to add 2 x Double2 and 1 x Layer attributes.4. Connect each of the Null's positions to the Double2 attributes.5. Connect the Ellipse to the Layer attribute.6. Copy and paste the below into the JavaScript Shape's Expression.7. Move the Nulls outside the Ellipse.*/function getPath() { var intersectionPath = n2.path; var path = new cavalry.Path() var line = new cavalry.Line(n0.x, n0.y, n1.x, n1.y); var intersections = intersectionPath.lineIntersections(line); for (let pt of intersections) { path.addEllipse(pt.x,pt.y,20,20); } return path;}getPath();pathIntersections(path:cavalry.Path) → array[object]
标题为“pathIntersections(path:cavalry.Path) → array[object]”的章节Returns an array of points at which this path and the given path intersect.
/*1. Create a Star, an Ellipse and a JavaScript Shape.2. Use the + button under the JavaScript Shape's 'Javascript' tab to add 2 x Layer attributes.3. Connect the Star and Ellipse to the new Layer attribute.4. Copy and paste the below into the JavaScript Shape's Expression.5. Increase the Star's Radius.*/function getPath() { var pathA = n1.path; var pathB = n2.path; var intersections = pathA.pathIntersections(pathB); var path = new cavalry.Path() for (let pt of intersections) { path.addEllipse(pt.x,pt.y,20,20); } return path;}getPath();relax(iterations:int, radius:number, relaxationStrength:number)
标题为“relax(iterations:int, radius:number, relaxationStrength:number)”的章节Relax the points in the path away from each other.
// See 'Create > Demo Scenes > JavaScript > Differential Line Growth'.smooth(iterations:int, smoothStrength:number)
标题为“smooth(iterations:int, smoothStrength:number)”的章节Smooths the points by averaging their positions.
// See 'Create > Demo Scenes > JavaScript > Differential Line Growth'.scatter(numberOfPoints:int, seed:int, sequence:int, relaxIterations:int, relaxDistance:number) → array[object]
标题为“scatter(numberOfPoints:int, seed:int, sequence:int, relaxIterations:int, relaxDistance:number) → array[object]”的章节Scatter points inside the path via dart throwing. Points are relaxed by default.
length() → number
标题为“length() → number”的章节Return the length of the path.
pointAtParam(param:number) → {x:number, y:number}
标题为“pointAtParam(param:number) → {x:number, y:number}”的章节Return the position of a point at a given parameter along the path.
tangentAtParam(param:number) → {x:number, y:number}
标题为“tangentAtParam(param:number) → {x:number, y:number}”的章节Return a point object with x,y variables that corresponds to a tangent a given parameter along the path.
normalAtParam(param:number) → {x:number, y:number}
标题为“normalAtParam(param:number) → {x:number, y:number}”的章节Calculate the normal vector at the given parameter along the path.
angleAtParam(param:number) → number
标题为“angleAtParam(param:number) → number”的章节Return an angle in degrees representing the tangent a given parameter along the path.
paramAtLength(length:number) → number
标题为“paramAtLength(length:number) → number”的章节Given a length, return the corresponding parameter value for that length value.
findClosestPoint(x:number, y:number) → {position:{x:number, y:number},tangent:{x:number,y:number},normal:{x:number,y:number}}
标题为“findClosestPoint(x:number, y:number) → {position:{x:number, y:number},tangent:{x:number,y:number},normal:{x:number,y:number}}”的章节Find the closest point on a path to the given x,y values and return an object with position, normal and tangent variables, each of which has x,y variables.
mergeOverlaps()
标题为“mergeOverlaps()”的章节Converts the path into a set of non-overlapping contours that describe the same area as the original path.
reverse()
标题为“reverse()”的章节Reverses the Path direction.
var path = new cavalry.Path();path.moveTo(0.,0.);path.lineTo(0.,-100.);path.lineTo(300.,-100.);path.cubicTo(210., 110., 240., 140., 280., 260);path.close();console.log(path.isClockwise());path.reverse();console.log(path.isClockwise());isClockwise() → bool
标题为“isClockwise() → bool”的章节Returns true if the path is clockwise.
var path = new cavalry.Path();path.moveTo(0.,0.);path.lineTo(0.,-100.);path.lineTo(300.,-100.);path.cubicTo(210., 110., 240., 140., 280., 260);path.close();console.log(path.isClockwise());path.reverse();console.log(path.isClockwise());applyMatrix(matrix:object)
标题为“applyMatrix(matrix:object)”的章节Multiply the path point positions by a matrix.
var mat = new cavalry.Matrix();mat.setRotation(90);var path = new cavalry.Path();path.addText("hello world", 72, 0, 0);path.applyMatrix(mat);api.createEditable(path, "My Path");Line Class
标题为“Line Class”的章节Represent a line defined by two points with various geometric operations.
var line = new cavalry.Line(0,0,100,100);console.log(line.length())var line = new cavalry.Line(0,0,100,100);console.log(JSON.stringify(line.closestPointTo({"x":100,"y":50})))For examples see the Closest Point, Intersections and Spikes Demo Scenes via the Create > Demo Scenes > JavaScript menu.
length() → number
标题为“length() → number”的章节Gets the length of the line.
angle() → number
标题为“angle() → number”的章节Returns the angle of the line in degrees.
setLength(length:number)
标题为“setLength(length:number)”的章节Sets the length of the line.
setAngle(angle:number)
标题为“setAngle(angle:number)”的章节Sets the angle of the line in radians.
start() → {x:number,y:number}
标题为“start() → {x:number,y:number}”的章节Retrieves the start point of the line.
end() → {x:number,y:number}
标题为“end() → {x:number,y:number}”的章节Retrieves the end point of the line.
delta() → {x:number,y:number}
标题为“delta() → {x:number,y:number}”的章节Calculates the delta (difference in coordinates) between the start and end points of the line.
pointAt(param:number) → {x:number,y:number}
标题为“pointAt(param:number) → {x:number,y:number}”的章节Calculates the point at a given parameter along the line.
normalAt(param:number) → {x:number,y:number}
标题为“normalAt(param:number) → {x:number,y:number}”的章节Calculates the normal vector at a given parameter along the line.
translate({x:number,y:number})
标题为“translate({x:number,y:number})”的章节Translates the line by a given point vector.
distance({x:number,y:number}) → number
标题为“distance({x:number,y:number}) → number”的章节Calculates the shortest distance from the line to a given point.
closestPointTo ({x:number,y:number}) → {x:number,y:number}
标题为“closestPointTo ({x:number,y:number}) → {x:number,y:number}”的章节Calculates the closest point on the line to a given point.
lineIntersection(line:cavalry.Line) → {x:number,y:number}
标题为“lineIntersection(line:cavalry.Line) → {x:number,y:number}”的章节Returns the point at which two lines intersect, or null if there’s no intersection.
Point Cloud Class
标题为“Point Cloud Class”的章节Represents a collection of Points. These objects can be used as Distributions on the Duplicator (for example) via a Custom Distribution.
See Create > Demo Scenes > JavaScript > Spirograph Distribution or Create > Demo Scenes > JavaScript > Circle Packing with Gradient Descent for examples.
appendPoint(point:Point)
标题为“appendPoint(point:Point)”的章节Append a Point to the cloud.
appendRotation(rotation:number)
标题为“appendRotation(rotation:number)”的章节Append a rotation in degrees to the cloud. Make sure there’s a corresponding point.
appendSize(point:Point)
标题为“appendSize(point:Point)”的章节Append a size to the cloud. Make sure there’s a corresponding point.
Point Class
标题为“Point Class”的章节Represents a simple point for use in a Point Cloud.
See Create > Demo Scenes > JavaScript > Spirograph Distribution or Create > Demo Scenes > JavaScript > Circle Packing with Gradient Descent for examples.
Mesh Class
标题为“Mesh Class”的章节The Mesh class is a container which can be used to construct multiple Paths and include materials. If unique Materials for each Path are not required, use path.append() to add Paths together.
addPath(path:Path, material?:Material)
标题为“addPath(path:Path, material?:Material)”的章节Add a Path to a Mesh with an optional Material. If no material is provided, the path inherits its appearance from the parent mesh or the shape’s Fill/Stroke settings.
count() → int
标题为“count() → int”的章节Returns the number of paths in a Mesh.
empty() → bool
标题为“empty() → bool”的章节Returns whether or not the Mesh is empty.
clear()
标题为“clear()”的章节Erases all Paths on the Mesh.
getBoundingBox() → {x:number, y:number, width:number, height:number, centre:{x:number, y:number}, left:number, right:number, top:number, bottom:number}
标题为“getBoundingBox() → {x:number, y:number, width:number, height:number, centre:{x:number, y:number}, left:number, right:number, top:number, bottom:number}”的章节Returns a standard bounding box object.
getPathDataAtIndex(index: int) → array[object]
标题为“getPathDataAtIndex(index: int) → array[object]”的章节Returns a pathData array, which includes verbs and points. This data is designed for point level modification.
setPathAtIndex(index: int, path:Path object)
标题为“setPathAtIndex(index: int, path:Path object)”的章节Overwrite a path at a given index with a different Path object.
setPathDataAtIndex(index: int, pathData:object)
标题为“setPathDataAtIndex(index: int, pathData:object)”的章节Sets the pathData at a given depth and index.
setMaterialAtIndex(index: int, material: Material object)
标题为“setMaterialAtIndex(index: int, material: Material object)”的章节Overwrites the material at a given index with a different Material object.
function getMesh() { var path = new cavalry.Path() path.addEllipse(0,0,100,200); var mesh = new cavalry.Mesh(); var material = new cavalry.Material(); material.fillColor = "#ff24e0"; material.stroke = true; material.strokeColor = "#000000"; material.strokeWidth = 10; mesh.addPath(path, material); return mesh;}getMesh();getPathAtIndex(index:int) → Path object
标题为“getPathAtIndex(index:int) → Path object”的章节Retrieves the Path object at the specified index. Useful for adding to a path.
// Open 'Create > Demo Scenes > JavaScript > Spikes'.addChildMesh(mesh:Mesh)
标题为“addChildMesh(mesh:Mesh)”的章节Adds a child-mesh to this Mesh.
clearChildMeshes()
标题为“clearChildMeshes()”的章节Deletes all the child-meshes on this Mesh.
childMeshCount() → int
标题为“childMeshCount() → int”的章节Returns the number of child-meshes.
getChildMeshAtIndex(index:int) → Mesh
标题为“getChildMeshAtIndex(index:int) → Mesh”的章节Returns the child-mesh at the given index.
setChildMeshAtIndex(index:int, mesh:Mesh)
标题为“setChildMeshAtIndex(index:int, mesh:Mesh)”的章节Sets the child-mesh at the given index. Used when modifying mesh hierarchies, such as in JavaScript Deformers.
getFlattenedPath() → Path
标题为“getFlattenedPath() → Path”的章节Returns a Path representing the combined geometry of this mesh and all child meshes.
Material Class
标题为“Material Class”的章节Add material (Fill and Stroke) properties to a Mesh.
fill
标题为“fill”的章节Enable Fill. bool = true.
stroke
标题为“stroke”的章节Enable Stroke. bool = false.
fillColor
标题为“fillColor”的章节Set the Fill’s color. hex
strokeColor
标题为“strokeColor”的章节Set the Stroke’s color. hex
strokeWidth
标题为“strokeWidth”的章节Set the Stroke’s width. number
trim
标题为“trim”的章节Enable trim. bool
trimStart
标题为“trimStart”的章节Set the start point of the trim (0..1). number
trimEnd
标题为“trimEnd”的章节Set the end point of the trim (0..1). number
trimTravel
标题为“trimTravel”的章节Move the trim along the path. 1.0 is a complete cycle of a closed path. number
trimReversed
标题为“trimReversed”的章节Reverses the path direction for the trim effect. bool
// Example using the n0 Attribute to control the trim of a JavaScript Shape.// Uncheck the JavaScript Shape's Fill (under the Fill tab).function getMesh() { var path = new cavalry.Path() path.addEllipse(0,0,100,200); var mesh = new cavalry.Mesh(); var material = new cavalry.Material(); material.fillColor = "#ff24e0"; material.stroke = true; material.strokeColor = "#000000"; material.strokeWidth = 10; material.trim = true; material.trimStart = 0.45; material.trimEnd = 0.75; material.trimTravel = n0*0.01; mesh.addPath(path, material); return mesh;}getMesh();Matrix Class
标题为“Matrix Class”的章节Represent a 2D transformation matrix.
setPosition(x:number, y:number)
标题为“setPosition(x:number, y:number)”的章节Sets the position (translation) of the matrix.
setRotation(angle:number)
标题为“setRotation(angle:number)”的章节Sets the rotation of the matrix in degrees.
setScale(x:number, y:number)
标题为“setScale(x:number, y:number)”的章节Sets the scale factors of the matrix.
setSkew(x:number, y:number)
标题为“setSkew(x:number, y:number)”的章节Sets the skew factors of the matrix.
skew() -> {x:number, y:number}
标题为“skew() -> {x:number, y:number}”的章节Return the skew.
scale() → object
标题为“scale() → object”的章节Gets the scale factors of the matrix.
position() → {x:number, y:number}
标题为“position() → {x:number, y:number}”的章节Gets the position (translation) of the matrix.
rotation() → number
标题为“rotation() → number”的章节Gets the rotation of the matrix in degrees.
multiply(matrix:matrix) → matrix
标题为“multiply(matrix:matrix) → matrix”的章节Returns a new matrix that is the result of multiplying this matrix with another matrix.
inverted() → matrix
标题为“inverted() → matrix”的章节Returns a new matrix that is the inverse of this matrix.
invert()
标题为“invert()”的章节Inverts this matrix in place.
isFinite() → bool
标题为“isFinite() → bool”的章节Checks if all elements of the matrix are finite.
isIdentity() → bool
标题为“isIdentity() → bool”的章节Checks if the matrix is an identity matrix.
mapRect(rect:object) → {x:number, y:number, width:number, height:number, centre:{x:number, y:number}, left:number, right:number, top:number, bottom:number}
标题为“mapRect(rect:object) → {x:number, y:number, width:number, height:number, centre:{x:number, y:number}, left:number, right:number, top:number, bottom:number}”的章节Maps a rectangle {x:number, y:number, width:number, height:number} using this matrix and returns the resulting rectangle.
mapPoint(point:object) → {x:number, y:number}
标题为“mapPoint(point:object) → {x:number, y:number}”的章节Maps a point using this matrix and returns the resulting point.
mapPoints(points:array[object]) → array[object]
标题为“mapPoints(points:array[object]) → array[object]”的章节Maps an array of points using this matrix and returns the resulting array of points.
var mat = new cavalry.Matrix();mat.setRotation(180);mat.setScale(2,2);var pt = {"x": 50, "y":0}var finalPt = mat.mapPoint(pt);console.log(JSON.stringify(finalPt));setFromArray([number])
标题为“setFromArray([number])”的章节Set the 3x3 matrix from an array of 9 numbers.
Example usage:
// Get the global position of a Shapevar shapeId = api.primitive("circle", "Circle");api.set(shapeId, {"position": [500,500]});var groupId = api.create("group");api.parent(shapeId, groupId);api.set(groupId, {"rotation": 45});var matArray = api.get(shapeId, "globalTransform");var matrix = new cavalry.Matrix();matrix.setFromArray(matArray);console.log(JSON.stringify(matrix.position()));Math
标题为“Math”的章节random(min:number, max:number, seed:int, sequence:int) → number
标题为“random(min:number, max:number, seed:int, sequence:int) → number”的章节Returns a random number. The sequence argument is optional.
for (var i = 1; i < 10; i +=1){ console.log(cavalry.random(0, 10, i));}uniform(min:number, max:number, seed:int) → number
标题为“uniform(min:number, max:number, seed:int) → number”的章节Returns random numbers with a uniform distribution.
for (var i = 1; i < 10; i +=1){ console.log(cavalry.uniform(0, 10, i));}noise1d(x:number, seed:int, frequency:number) → number
标题为“noise1d(x:number, seed:int, frequency:number) → number”的章节Returns 1d Improved Perlin noise.
for (var i = 1; i < 10; i +=1){ console.log(cavalry.noise1d(i, 0, 1));}noise2d(x:number, y:number, seed:int, frequency:number) → number
标题为“noise2d(x:number, y:number, seed:int, frequency:number) → number”的章节Returns 2d Improved Perlin noise.
for (var i = 1; i < 10; i +=1){ console.log(cavalry.noise2d(i, api.getFrame(), 0, 1));}noise3d(x:number, y:number, z.number, seed:int, frequency:number) → number
标题为“noise3d(x:number, y:number, z.number, seed:int, frequency:number) → number”的章节Returns 3d Improved Perlin noise.
for (var i = 1; i < 10; i +=1){ console.log(cavalry.noise3d(i, i+100, api.getFrame(), 0, 0.1));}dist(x1:number, y1:number, x2:number, y2:number) → number
标题为“dist(x1:number, y1:number, x2:number, y2:number) → number”的章节Get the distance between two points.
var d = cavalry.dist(0,0,100,100)console.log(d);map(value:number, inMin:number, inMax:number, outMin:number, outMax:number) → number
标题为“map(value:number, inMin:number, inMax:number, outMin:number, outMax:number) → number”的章节Remap a value into a new range.
// remap 30 from the range 0..60 to the range 100..300. Prints 200.console.log(cavalry.map(30,0,60,100,300));norm(value:number, min:number, max:number) → number
标题为“norm(value:number, min:number, max:number) → number”的章节Normalise a value between 0..1.
// Prints 0.55;console.log(cavalry.norm(55,0,100));clamp(value:number, min:number, max:number) → number
标题为“clamp(value:number, min:number, max:number) → number”的章节Clamp a value min and max.
// Prints 100;console.log(cavalry.clamp(150,0,100));lerp(min:number, max:number, t:number) → number
标题为“lerp(min:number, max:number, t:number) → number”的章节Interpolate between a minimum and maximum value. The value returned is the value at t (between 0 and 1).
angleFromVector(x:number, y:number) → number
标题为“angleFromVector(x:number, y:number) → number”的章节Convert a vector into an angle (radians).
var ang = cavalry.angleFromVector(1,0);console.log(ang);var vec = cavalry.vectorFromAngle(ang);console.log(vec["x"]+" "+vec["y"]);vectorFromAngle(angle:number) → {x:number, y:number}
标题为“vectorFromAngle(angle:number) → {x:number, y:number}”的章节Convert an angle (radians) into a vector (x, y) with values between 0..1.
var ang = cavalry.angleFromVector(1,0);console.log(ang);var vec = cavalry.vectorFromAngle(ang);console.log(vec["x"]+" "+vec["y"]);radiansToDegrees(radians:number) → number
标题为“radiansToDegrees(radians:number) → number”的章节Convert a value from radians to degrees.
console.log(cavalry.radiansToDegrees(2));degreesToRadians(degrees:number) → number
标题为“degreesToRadians(degrees:number) → number”的章节Convert a value from degrees to radians.
console.log(cavalry.degreesToRadians(90));Color
标题为“Color”的章节rgbToHsv(r:number, g:number, b:number, normalised=true) → {h:number, s:number, v:number}
标题为“rgbToHsv(r:number, g:number, b:number, normalised=true) → {h:number, s:number, v:number}”的章节Convert an RGB color to HSV. If the optional normalised argument is set to false then RGB values should be within a range of 0..255 otherwise they should be within a range of 0..1.
var unscaled = cavalry.rgbToHsv(255,0,255, false);var scaled = cavalry.rgbToHsv(1,0,1, true);console.log('Unscaled = ' + JSON.stringify(unscaled) + ' - Scaled = ' + JSON.stringify(scaled));rgbToHex(r:number, g:number, b:number, normalised=true) → string
标题为“rgbToHex(r:number, g:number, b:number, normalised=true) → string”的章节Converts normalised RGB color values to their hex color string representation. Set the optional normalised argument to false to enter RGB values within a range of 0..255.
var label1 = new ui.Label('Unscaled');label1.setTextColor(cavalry.rgbToHex(255,0,255,false));ui.add(label1);var label2 = new ui.Label('Scaled');label2.setTextColor(cavalry.rgbToHex(1,0,1,true));ui.add(label2);ui.show();rgbaToHex(r:number, g:number, b:number, a:number, normalised=true) → string
标题为“rgbaToHex(r:number, g:number, b:number, a:number, normalised=true) → string”的章节Converts normalised RGBA color values to their hex color string representation. Set the optional normalised argument to false to enter RGBA values within a range of 0..255.
var hexColor = cavalry.rgbaToHex(255,36,224,50,false);console.log(hexColor);var shapeId = api.primitive("rectangle", "My Rect");api.set(shapeId, {"material.materialColor": hexColor});hsvToRgba(h:number, s:number, v:number, normalised=false) → {r:int, g:int, b:int, a:int}
标题为“hsvToRgba(h:number, s:number, v:number, normalised=false) → {r:int, g:int, b:int, a:int}”的章节Convert an HSV color value to its RGBA representation, optionally normalised to the range of 0..1. Values should be in the ranges H 0..360, S 0..1, V 0..1.
var result = cavalry.hsvToRgba(180,1,0.5);console.log(JSON.stringify(result));hsvToHex(h:number, s:number, v:number) → string
标题为“hsvToHex(h:number, s:number, v:number) → string”的章节Convert a HSV color to a Hex string. Values should be in the ranges H 0..360, S 0..1, V 0..1.
var result = cavalry.hsvToHex(108,0.85,1.0);console.log(result);hexToRgba(hex:string, normalised=false) → {r:int, g:int, b:int, a:int}
标题为“hexToRgba(hex:string, normalised=false) → {r:int, g:int, b:int, a:int}”的章节Converts a hex color value (e.g #4ffd7a) to its RGBA representation, optionally normalised to the range of 0..1. The hex string can optionally include alpha (e.g #4ffd7a7f)
var result = cavalry.hexToRgba("#4ffd7a7f");console.log(JSON.stringify(result));hexToHsv(hexValue:string) → {h:number, s:number, v:number}
标题为“hexToHsv(hexValue:string) → {h:number, s:number, v:number}”的章节Convert a Hex value (e.g #ffffff) color to HSV.
var result = cavalry.hexToHsv("#ff9801");console.log(JSON.stringify(result));nameThatColor(hexValue:string) → string
标题为“nameThatColor(hexValue:string) → string”的章节Returns a W3C color name that’s the closest match to the specified hex color.
console.log(cavalry.nameThatColor("#ff9801"));Text
标题为“Text”的章节fontExists(fontFamily:string, fontStyle:string) → bool
标题为“fontExists(fontFamily:string, fontStyle:string) → bool”的章节Returns true if a font is available to Cavalry.
console.log(cavalry.fontExists("Lato", "Regular")); // prints `true`getFontFamilies() → [string]
标题为“getFontFamilies() → [string]”的章节Returns a list of all the font families available to Cavalry.
console.log(cavalry.getFontFamilies());getFontStyles(string:fontFamily) → [string]
标题为“getFontStyles(string:fontFamily) → [string]”的章节Returns a list of all the available styles for the given font family.
console.log(cavalry.getFontStyles("Lato"));measureText(string:string, fontFamily:string, fontStyle:string, fontSize:int) → {width:number, height:number, x:number, y:number, centreX:number, centreY:number}
标题为“measureText(string:string, fontFamily:string, fontStyle:string, fontSize:int) → {width:number, height:number, x:number, y:number, centreX:number, centreY:number}”的章节Returns an object representing the bounding box of some text without the need to actually create a text shape.
- width - The width of the text
- height - The height of the text
- x - The left edge of the text
- y - The top edge of the text
- centreX - The average of the left and right edges
- centreY - The average of the top and bottom edges
var measure = cavalry.measureText("Some text to measure", "Lato", "Regular", 72);console.log(JSON.stringify(measure));fontMetrics(fontFamily:string, fontStyle:string, fontSize:int) → {top:number, ascent:number, descent:number, bottom:number, leading:int, averageCharacterWidth:number, maxCharacterWidth:number, xMin:number, xMax:number, xHeight:number, capHeight:number}
标题为“fontMetrics(fontFamily:string, fontStyle:string, fontSize:int) → {top:number, ascent:number, descent:number, bottom:number, leading:int, averageCharacterWidth:number, maxCharacterWidth:number, xMin:number, xMax:number, xHeight:number, capHeight:number}”的章节Returns an object containing information about the given font. The resulting metrics are scaled by the font size.
- top - greatest extent above origin of any glyph bounding box, typically negative; deprecated with variable fonts
- ascent - distance to reserve above baseline, typically negative
- descent - distance to reserve below baseline, typically positive
- bottom - greatest extent below origin of any glyph bounding box, typically positive; deprecated with variable fonts
- leading - distance to add between lines, typically positive or zero
- averageCharacterWidth - average character width, zero if unknown
- maxCharacterWidth - maximum character width, zero if unknown
- xMin - greatest extent to left of origin of any glyph bounding box, typically negative; deprecated with variable fonts
- xMax - greatest extent to right of origin of any glyph bounding box, typically positive; deprecated with variable fonts
- xHeight - height of lower-case ‘x’, zero if unknown, typically negative
- capHeight - height of an upper-case letter, zero if unknown, typically negative
var metrics = cavalry.fontMetrics("Lato", "Regular", 72);console.log(JSON.stringify(metrics));Utilities
标题为“Utilities”的章节versionLessThan(version:string) → bool
标题为“versionLessThan(version:string) → bool”的章节This will return true if the version of Cavalry in use is less than the specified version. This is useful to add support for features in scripts that depend on the version of Cavalry.
// This will return true in Cavalry 1.3.1, and false in Cavalry 1.5.0console.log(cavalry.versionLessThan("1.4.0"));Cavalry uses Semantic Versioning for version numbers.
MAJOR.MINOR.PATCH (e.g. 1.5.0) is used for official releases.
MAJOR.MINOR.PATCH.PRE-RELEASE-TYPE.NUMBER (e.g. 2.0.0-beta.1) is used for pre-release builds.