Cavalry Module
Pro features are only available with a Professional licence. To upgrade, visit cavalry.scenegroup.co.
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).
Member Functions
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:
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 so
api.createEditable(path, "My Path");
moveTo(x:number, y:number)
Start a new contour.
lineTo(x:number, y:number)
Draw a line to x,y.
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.
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.
quadTo(x1:number, y1:number, x2:number, y2:number)
Add a quadratic bézier curve to the path.
convertConicsToQuads()
Convert any conic verbs to quad verbs. This might be useful as not all features in Cavalry support conic verbs.
close()
Close the path.
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)
Convenience method for drawing a rectangle.
addEllipse(centreX:number, centreY:number, radiusX:number, radiusY:number)
Convenience method for drawing an ellipse.
clear()
Empty the path.
isClosed → bool
Returns a boolean signifying if the path is closed.
translate(x:number, y:number)
Move the path by x
and y
.
rotate(degrees:number)
Rotate the path.
scale(x:number, y:number)
Scale the path.
append(pathToAdd:path)
Add one path to another.
intersect(intersectPath:path)
Perform a Boolean intersection.
unite(unitePath:path)
Perform a Boolean unite.
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()
Resample lines as curves (the algorithm used by the Pencil Tool).
convertToLines(linesPerCurve:int)
Convert (vectorise) any curves into a series of lines.
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 Object
var js = path.toObject();
// Convert from a saved object
path.fromObject(js);
console.log(path.length);
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 Object
var js = path.toObject();
// Convert from a saved object
path.fromObject(js);
console.log(path.length);
arcTo(x1:number, y1:number, x2:number, y2:number, radius:number)
Draw an arc with two control points and a radius.
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}
Return the bounding box of a path.
var path = new cavalry.Path();
path.addText("Some text!", 22, 0, 10);
let bbox = path.boundingBox();
console.log(JSON.stringify(bbox));
empty() → bool
Return if a path is empty or not.
pointCount() → int
Return the number of points in the path.
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
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 apoint
object (with x and y variables).lineTo
: contains apoint
object (with x and y variables).quadTo
: contains acp1
object representing the control point (with x and y variables) along with apoint
object (with x and y variables). This is the end point of thequadTo
verb.cubicTo
: containscp1
andcp2
objects representing the first and second control points (both with x and y variables) along with apoint
object (with x and y variables). This is the end point of thecubicTo
verb.close
: contains no points.
setPathData(data:object)
Set the path based on a pathData object.
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)
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)
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(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(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 the points in the path away from each other.
// See 'Create > Demo Scenes > JavaScript > Differential Line Growth'.
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 points inside the path via dart throwing. Points are relaxed by default.
length() → number
Return the length of the path.
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}
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}
Calculate the normal vector at the given parameter along the path.
angleAtParam(param:number) → number
Return an angle in degrees representing the tangent a given parameter along the path.
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}}
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()
Converts the path into a set of non-overlapping contours that describe the same area as the original path.
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
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)
Multiply the path point positions by a matrix.
let 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
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
Gets the length of the line.
angle() → number
Returns the angle of the line in degrees.
setLength(length:number)
Sets the length of the line.
setAngle(angle:number)
Sets the angle of the line in radians.
start() → {x:number,y:number}
Retrieves the start point of the line.
end() → {x:number,y:number}
Retrieves the end point of the line.
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}
Calculates the point at a given parameter along the line.
normalAt(param:number) → {x:number,y:number}
Calculates the normal vector at a given parameter along the line.
translate({x:number,y:number})
Translates the line by a given point vector.
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}
Calculates the closest point on the line to a given point.
lineIntersection(cavalry.Line) → {x:number,y:number}
Returns the point at which two lines intersect, or null if there's no intersection.
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)
Append a Point to the cloud.
appendRotation(rotation:number)
Append a rotation in degrees to the cloud. Make sure there's a corresponding point.
appendSize(point:Point)
Append a size to the cloud. Make sure there's a corresponding point.
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
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)
Add a Path and Material to a Mesh.
count() → int
Returns the number of paths in a Mesh.
empty() → bool
Returns whether or not the Mesh is empty.
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}
Returns a standard bounding box 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)
Overwrite a path at a given index with a different Path object.
setPathDataAtIndex(index: int, pathData:object)
Sets the pathData at a given depth and index.
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
Retrieves the Path object at the specified index. Useful for adding to a path.
// Open 'Create > Demo Scenes > JavaScript > Spikes'.
addChildMesh(mesh:Mesh)
Adds a child-mesh to this Mesh.
clearChildMeshes()
Deletes all the child-meshes on this Mesh.
childMeshCount() → int
Returns the number of child-meshes.
getChildMeshAtIndex(index:int) → Mesh
Returns the child-mesh at the given index.
Material Class
Add material (Fill and Stroke) properties to a Mesh.
fill
Enable Fill. bool = true
.
stroke
Enable Stroke. bool = false
.
fillColor
Set the Fill's color. hex
strokeColor
Set the Stroke's color. hex
strokeWidth
Set the Stroke's width. number
trim
Enable trim. bool
trimStart
Set the start point of the trim (0..1). number
trimEnd
Set the end point of the trim (0..1). number
trimTravel
Move the trim along the path. 1.0 is a complete cycle of a closed path. number
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
Represent a 2D transformation matrix.
setPosition(x:number, y:number)
Sets the position (translation) of the matrix.
setRotation(angle:number)
Sets the rotation of the matrix in degrees.
setScale(x:number, y:number)
Sets the scale factors of the matrix.
setSkew(x:number, y:number)
Sets the skew factors of the matrix.
skew() -> {x:number, y:number}
Return the skew.
scale() → object
Gets the scale factors of the matrix.
position() → {x:number, y:number}
Gets the position (translation) of the matrix.
rotation() → number
Gets the rotation of the matrix in degrees.
multiply(matrix:matrix) → matrix
Returns a new matrix that is the result of multiplying this matrix with another matrix.
inverted() → matrix
Returns a new matrix that is the inverse of this matrix.
invert()
Inverts this matrix in place.
isFinite() → bool
Checks if all elements of the matrix are finite.
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}
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}
Maps a point using this matrix and returns the resulting point.
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);
let pt = {"x": 50, "y":0}
let finalPt = mat.mapPoint(pt);
console.log(JSON.stringify(finalPt));
setFromArray([number])
Set the 3x3 matrix from an array of 9 numbers.
Example usage:
// Get the global position of a Shape
let shapeId = api.primitive("circle", "Circle");
api.set(shapeId, {"position": [500,500]});
let groupId = api.create("group");
api.parent(shapeId, groupId);
api.set(groupId, {"rotation": 45});
let matArray = api.get(shapeId, "globalTransform");
let matrix = new cavalry.Matrix();
matrix.setFromArray(matArray);
console.log(JSON.stringify(matrix.position()));
Math
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
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
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
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
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
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
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
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 a value min and max.
// Prints 100;
console.log(cavalry.clamp(150,0,100));
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
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}
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
Convert a value from radians to degrees.
console.log(cavalry.radiansToDegrees(2));
degreesToRadians(degrees:number) → number
Convert a value from degrees to radians.
console.log(cavalry.degreesToRadians(90));
Color
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
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.
const label1 = new ui.Label('Unscaled');
label1.setTextColor("#"+cavalry.rgbToHex(255,0,255,false));
ui.add(label1);
const 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
Converts normalised RGBA 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.
let hexColor = cavalry.rgbaToHex(255,36,224,50,false);
console.log(hexColor);
let 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}
Convert an HSV color value to its RGBA representation, optionally normalised to the range of 0..1.
var result = cavalry.hsvToRgba(180,1,0.5);
console.log(JSON.stringify(result));
hsvToHex(h:number, s:number, v:number) → string
Convert a HSV color to a Hex string.
var result = cavalry.rgbToHex(79,253,122);
console.log(result);
hexToRgba(hex:string, normalised=false) → {r:int, g:int, b:int, a:int}
Converts a hex color value (e.g #ffffff
) to its RGBA representation, optionally normalised to the range of 0..1.
var result = cavalry.hexToRgba("#fc5900");
console.log(JSON.stringify(result));
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));
Text
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]
Returns a list of all the font families available to Cavalry.
console.log(cavalry.getFontFamilies());
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}
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
const 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}
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
const metrics = cavalry.fontMetrics("Lato", "Regular", 72);
console.log(JSON.stringify(metrics));
Utilities
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.0
console.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.