跳转到内容

Cavalry 模块

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.

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.

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

Start a new contour.

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.

Convert any conic verbs to quad verbs. This might be useful as not all features in Cavalry support conic verbs.

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.

Empty the path.

Returns a boolean signifying if the path is closed.

Move the path by x and y.

Rotate the path.

Scale the path.

Add one path to another.

Perform a Boolean intersection.

Perform a Boolean unite.

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

Resample lines as curves (the algorithm used by the Pencil Tool).

Convert (vectorise) any curves into a series of lines.

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);

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);

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));

Return if a path is empty or not.

Return the number of points in the path.

Return if the point specified by x,y is inside the path (only works on a closed path).

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 a point object (with x and y variables).
  • lineTo: contains a point object (with x and y variables).
  • quadTo: contains a cp1 object representing the control point (with x and y variables) along with a point object (with x and y variables). This is the end point of the quadTo verb.
  • cubicTo: contains cp1 and cp2 objects representing the first and second control points (both with x and y variables) along with a point object (with x and y variables). This is the end point of the cubicTo verb.
  • close: contains no points.

Set the path based on a pathData object.

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

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'.

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.

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.

Return an angle in degrees representing the tangent a given parameter along the path.

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.

Converts the path into a set of non-overlapping contours that describe the same area as the original path.

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

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

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

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.

Gets the length of the line.

Returns the angle of the line in degrees.

Sets the length of the line.

Sets the angle of the line in radians.

Retrieves the start point of the line.

Retrieves the end point of the line.

Calculates the delta (difference in coordinates) between the start and end points of the line.

Calculates the point at a given parameter along the line.

Calculates the normal vector at a given parameter along the line.

Translates the line by a given point vector.

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.

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.

Append a Point to the cloud.

Append a rotation in degrees to the cloud. Make sure there’s a corresponding point.

Append a size to the cloud. Make sure there’s a corresponding point.

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.

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.

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.

Returns the number of paths in a Mesh.

Returns whether or not the Mesh is empty.

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.

Overwrite a path at a given index with a different Path 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();

Retrieves the Path object at the specified index. Useful for adding to a path.

// Open 'Create > Demo Scenes > JavaScript > Spikes'.

Adds a child-mesh to this Mesh.

Deletes all the child-meshes on this Mesh.

Returns the number of child-meshes.

Returns the child-mesh at the given index.

Sets the child-mesh at the given index. Used when modifying mesh hierarchies, such as in JavaScript Deformers.

Returns a Path representing the combined geometry of this mesh and all child meshes.

Add material (Fill and Stroke) properties to a Mesh.

Enable Fill. bool = true.

Enable Stroke. bool = false.

Set the Fill’s color. hex

Set the Stroke’s color. hex

Set the Stroke’s width. number

Enable trim. bool

Set the start point of the trim (0..1). number

Set the end point of the trim (0..1). number

Move the trim along the path. 1.0 is a complete cycle of a closed path. number

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

Represent a 2D transformation matrix.

Sets the position (translation) of the matrix.

Sets the rotation of the matrix in degrees.

Sets the scale factors of the matrix.

Sets the skew factors of the matrix.

Return the skew.

Gets the scale factors of the matrix.

Gets the position (translation) of the matrix.

Gets the rotation of the matrix in degrees.

Returns a new matrix that is the result of multiplying this matrix with another matrix.

Returns a new matrix that is the inverse of this matrix.

Inverts this matrix in place.

Checks if all elements of the matrix are finite.

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.

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));

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).

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"]);

Convert a value from radians to degrees.

console.log(cavalry.radiansToDegrees(2));

Convert a value from degrees to radians.

console.log(cavalry.degreesToRadians(90));

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));

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`

Returns a list of all the font families available to Cavalry.

console.log(cavalry.getFontFamilies());

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));

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.