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.
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
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()));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"));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.