Two.js is a two-dimensional drawing api geared towards modern web browsers. It is renderer agnostic enabling the same api to draw in multiple contexts: svg
, canvas
, and webgl
.
Download
Development Version
Uncompressed with comments about 128kb
Production Version
Minified using Closure Compiler about 50kb
Prior to v0.7.0-alpha.1 Two.js requires Underscore.js and Backbone.js Events. If you're already loading these files elsewhere then you can build the project yourself and get the file size even smaller. For more information on custom builds check out the source on github.
Overview
-
Focus on Vector Shapes
Two.js is deeply inspired by flat motion graphics. As a result, two.js aims to make the creation and animation of flat shapes easier and more concise.
-
Scenegraph
At its core two.js relies on a scenegraph. This means that when you draw or create an object (a
Two.Path
orTwo.Group
), two actually stores and remembers that. After you make the object you can apply any number of operations to it — e.g:rotation
,translation
,scale
, etc.. -
Animation Loop
Two.js has a built in animation loop. It is simple in nature and can be automated or paired with another animation library. For more information check out the examples.
-
SVG Interpreter
Two.js features a
Scalable Vector Graphics Interpreter
. This means developers and designers alike can create SVG elements in commercial applications like Adobe Illustrator and bring them into your two.js scene. For more information check out the examples.
Basic Usage
In order to start any of these demos you'll want to download two.js and add it to your <html>
document. Once downloaded add this tag to the <head>
of your document: <script src="./path-to-two/two.js"></script>
. When you visit the page, you should be able to open up the console and type Two
. If this returns a function then you're ready to begin!
Drawing Your First Shapes
Before we get into all the fancy animating it's good to get a feel for how to make shapes in two.js. In order to do this we need to have an instance of two. This sets up a dom element that contains either an svg
or canvas
element to add to the webpage. The two object has a scene
which holds all shapes as well as methods for creating shapes.
For a list of all properties and construction parameters check out the documentation.
Shapes and Groups
Adding shapes to groups makes managing multiple shapes easier and more sane. Group's provide an easy way to move your content through translation
, rotation
, and scale
. These operations emit from the coordinate space (0, 0)
. In the example below we can see that the initial orientation of the circle and rectangle changed from the first example. These shapes are oriented around (0, 0)
, which allows us to transform the group around the centeroid of the shapes. In addition Group's styling operations trickle down and apply to each shape.
All rendered objects in two.js are a child of a group. Every two instance has a property scene
. This property is a root-level Two.Group
and can act as a camera through the same transformations described above.
Adding Motion
Finally, let's add some motion to our shapes. So far the examples use two.update();
to draw content to the screen. The instance of two.js has two particular methods for animation. The first is two.play();
which calls two.update();
at 60fps. This rate, however, will slowdown if there's too much content to render per frame.
The second method is two.bind();
This method takes a string
as its first parameter indicating what event to listen to and a function
as its second argument delineating what to do when the event described in the first parameter happens. To sync a function with the animation loop simply invoke two.bind('update', referenceToFunction);
as outlined below:
For a complete list of events that can be bound to an instance of two check out the documentation.
Examples
For even more examples check out the example page here.
Projects
For even more projects and information to submit your projects built with two.js check out the project page here.
Documentation
- Two
- Two.Path
- Two.Line
- Two.Rectangle
- Two.RoundedRectangle
- Two.Ellipse
- Two.Star
- Two.Polygon
- Two.Group
- Two.Vector
- Two.Anchor
- Two.Stop
- Two.LinearGradient
- Two.RadialGradient
- Two.Text
Two
-
When you import the library Two is a
window
level class that serves as the main interaction point for the project. It exposes a number of methods and properties. These make it possible to draw, but also afford other capabilities such as augmenting the drawing space. Below are the documented properties and features of theTwo
class. Unless specified methods return their instance ofTwo
for the purpose of chaining. -
construction
var two = new Two(params);
Create a new instance of
Two
whereparams
is a JavaScript object with several optional parameters listed below:-
type
params.type
Set the type of renderer for the instance: svg, webgl, canvas, etc.. Applicable types are carried within
Two.Types
. Default type isTwo.Types.svg
. -
width
params.width
Set the width of the drawing space. Disregarded if
params.fullscreen
is set totrue
. Default width is640
pixels. -
height
params.height
Set the height of the drawing space. Disregarded if
params.fullscreen
is set totrue
. Default height is480
pixels. -
autostart
params.autostart
A boolean to automatically add the instance to draw on
requestAnimationFrame
. This is a convenient substitute so you don't have to calltwo.play()
. -
fullscreen
params.fullscreen
A boolean to set the drawing space of the instance to be fullscreen or not. If set to
true
thenwidth
andheight
parameters will not be respected. -
ratio
params.ratio
Set the resolution ratio for
canvas
andwebgl
renderers. If left blank two.js automatically infers the ratio based on thedevicePixelRatio
api.
-
-
type
two.type
A string representing which type of renderer the instance has implored.
-
frameCount
two.frameCount
A number representing how many frames have elapsed.
-
timeDelta
two.timeDelta
A number representing how much time has elapsed since the last frame in milliseconds.
-
width
two.width
The width of the instance's dom element.
-
height
two.height
The height of the instance's dom element.
-
playing
two.playing
A boolean representing whether or not the instance is being updated through the automatic
requestAnimationFrame
. -
renderer
two.renderer
The instantiated rendering class for the instance. For a list of possible rendering types check out
Two.Types
. -
scene
two.scene
The base level
Two.Group
which houses all objects for the instance. Because it is aTwo.Group
transformations can be applied to it that will affect all objects in the instance. This is handy as a makeshift camera. -
appendTo
two.appendTo(domElement);
A convenient method to append the instance's dom element to the page. It's required to add the instance's dom element to the page in order to see anything drawn.
-
play
two.play();
This method adds the instance to the
requestAnimationFrame
loop. In affect enabling animation for this instance. -
pause
two.pause();
This method removes the instance from the
requestAnimationFrame
loop. In affect halting animation for this instance. -
update
two.update();
This method updates the dimensions of the drawing space, increments the
tick
for animation, and finally callstwo.render()
. When using the built-inrequestAnimationFrame
hook,two.play()
, this method is invoked for you automatically. -
render
two.render();
This method makes the instance's renderer draw. It should be unnecessary to invoke this yourself at anytime.
-
add
two.add(objects);
Add one or many shapes / groups to the instance. Objects can be added as arguments,
two.add(o1, o2, oN)
, or as an array depicted above. -
remove
two.remove(objects);
Remove one or many shapes / groups from the instance. Objects can be removed as arguments,
two.remove(o1, o2, oN)
, or as an array depicted above. -
clear
two.clear();
Removes all objects from the instance's scene. If you intend to have the browser garbage collect this, don't forget to delete the references in your application as well.
-
makeLine
two.makeLine(x1, y1, x2, y2);
Draws a line between two coordinates to the instance's drawing space where
x1
,y1
are the x, y values for the first coordinate andx2
,y2
are the x, y values for the second coordinate. It returns aTwo.Line
object. -
makeRectangle
two.makeRectangle(x, y, width, height);
Draws a rectangle to the instance's drawing space where
x
,y
are the x, y values for the center point of the rectangle andwidth
,height
represents the width and height of the rectangle. It returns aTwo.Rectangle
object. -
makeRoundedRectangle
two.makeRoundedRectangle(x, y, width, height, radius);
Draws a rounded rectangle to the instance's drawing space where
x
,y
are the x, y values for the center point of the rectangle andwidth
,height
represents the width and height of the rectangle. Lastly, theradius
parameter defines what the miter radius of the rounded corner is. It returns aTwo.RoundedRectangle
object. -
makeCircle
two.makeCircle(x, y, radius);
Draws a circle to the instance's drawing space where
x
,y
are the x, y values for the center point of the circle andradius
is the radius of the circle. It returns aTwo.Circle
object. -
makeEllipse
two.makeEllipse(x, y, width, height);
Draws an ellipse to the instance's drawing space where
x
,y
are the x, y values for the center point of the ellipse andwidth
,height
are the dimensions of the ellipse. It returns aTwo.Ellipse
object. -
makeStar
two.makeStar(ox, oy, or, ir, sides);
Draws a star to the instance's drawing space where
ox
,oy
are the x, y values for the center point of the star andor
,ir
are the outer and inner radii for the star, andsides
are how many points the star has. It returns aTwo.Star
object. -
makePolygon
two.makePolygon(ox, oy, r, sides);
Draws a polygon to the instance's drawing space where
ox
,oy
are the x, y values for the center of the polygon,r
is the radius, andsides
are how many sides the polygon has. It returns aTwo.Polygon
object. -
makeArcSegment
two.makeArcSegment(ox, oy, ir, or, sa, ea, res);
Draws an arc segment from center point
ox
,oy
with an inner and outer radius ofir
,or
. Lastly, you need to supply a start and ending anglesa
,ea
. Optionally, pass the resolution for how many points on the arc are desired. It returns aTwo.ArcSegment
object. -
makeCurve
two.makeCurve(x1, y1, x2, y2, xN, yN, open);
Draws a curved path to the instance's drawing space. The arguments are a little tricky. It returns a
Two.Path
object.The method accepts any amount of paired x, y values as denoted by the series above. It then checks to see if there is a final argument, a boolean
open
, which marks whether or not the shape should be open. Iftrue
the curve will have two clear endpoints, otherwise it will be closed.This method also recognizes the format
two.makeCurve(points, open)
where points is an array ofTwo.Anchor
's and open is an optional boolean describing whether or not to expose endpoints. It is imperative if you generate curves this way to make the list of pointsTwo.Anchor
's. -
makePath
two.makePath(x1, y1, x2, y2, xN, yN, open);
Draws a path to the instance's drawing space. The arguments are a little tricky. It returns a
Two.Path
object.The method accepts any amount of paired x, y values as denoted by the series above. It then checks to see if there is a final argument, a boolean
open
, which marks whether or not the shape should be open. Iftrue
the path will have two clear endpoints, otherwise it will be closed.This method also recognizes the format
two.makePath(points, open)
where points is an array ofTwo.Anchor
's and open is an optional boolean describing whether or not to expose endpoints. It is imperative if you generate curves this way to make the list of pointsTwo.Anchor
's.The
Two.Path
that this method creates is the base shape for all of the make functions. -
makeGroup
two.makeGroup(objects);
Adds a group to the instance's drawing space. While a group does not have any visible features when rendered it allows for nested transformations on shapes. See
Two.Group
for more information. It accepts an array of objects,Two.Path
s orTwo.Group
s. As well as a list of objects as the arguments,two.makeGroup(o1, o2, oN)
. It returns aTwo.Group
object. -
interpret
two.interpret(svgNode);
Reads an svg node and draws the svg object by creating
Two.Path
s andTwo.Group
s from the reference. It then adds it to the instance's drawing space. It returns aTwo.Group
object. -
bind
two.bind(event, callback);
Bind an event, string, to a callback function. Passing
"all"
will bind the callback to all events. Inherited from Backbone.js. -
unbind
two.unbind(event, callback);
Remove one or many callback functions. If callback is
null
it removes all callbacks for an event. If the event name is null, all callback functions for the instance are removed. This is highly discouraged. Inherited from Backbone.js. -
Array
Two.Array
A JavaScript
Float32Array
with graceful fallback to JavaScriptArray
. -
Collection
Two.Utils.Collection
A databound instance of an array, e.g: used for
vertices
attribute of aTwo.Path
. -
Types
Two.Types
A list of applicable types of rendering contexts. This is used to standardize the addresses of the various renderers. The types include
svg
,canvas
, andwebgl
. e.g:Two.Types.svg
-
Properties
Two.Properties
A list of renderer specific application properties.
-
Events
Two.Events
A list of actionable events triggered by a given instance. For the most part these are internal events in order to enable two-way databinding. Exceptions include
update
event on animation loop andresize
when the dimensions of the drawing space change. Related totwo.bind
andtwo.trigger
. -
Commands
Two.Commands
A list of commands that dictate how the various renderers draw
Two.Anchor
s. -
Resolution
Two.Resolution
A number representing how many subdivisions should be present during curve calculations.
-
Instances
Two.Instances
A running list of all instances created on the page.
-
noConflict
Two.noConflict();
Run two.js in
noConflict
mode, returning thetwo
variable to its previous owner. Returns a reference to theTwo
class. -
Utils
Two.Utils
A collection of utility functions and variables used throughout the project. This is where much of the algorithmic computation lies: computing curve handles, subdividing cubic bezier curves, interpretting svg nodes. Because of its complexity it's encouraged to look at the source code for further information.
-
Error
Two.Error(message);
A two.js specific custom error handler. Takes a message, string, to display in the console to developers.
Two.Path
-
This is the base class for creating all drawable shapes in two.js. Unless specified methods return their instance of
Two.Path
for the purpose of chaining. -
construction
var path = new Two.Path(vertices, closed, curved, manual);
A path takes an array of
vertices
which are made up ofTwo.Anchor
s. This is essential for the two-way databinding. It then takes two booleans,closed
andcurved
which delineate whether the shape should be closed (lacking endpoints) and whether the shape should calculate curves or straight lines between the vertices. Finally, manual is an optional argument if you'd like to override the default behavior of two.js and handle anchor positions yourself. Generally speaking, this isn't something you need to deal with, although some great usecases arise from this customability, e.g: advanced curve manipulation.If you are constructing groups this way instead of
two.makePath()
, then don't forget to add the group to the instance's scene,two.add(group)
. -
id
path.id
The id of the path. In the svg renderer this is the same number as the
id
attribute given to the corresponding node. i.e: ifpath.id = 4
thendocument.querySelector('#two-' + group.id)
will return the corresponding svg node. -
stroke
path.stroke
A string representing the color for the stroke of the path. All valid css representations of color are accepted.
-
fill
path.fill
A string representing the color for the area of the vertices. All valid css representations of color are accepted.
-
linewidth
path.linewidth
A number representing the thickness the path's strokes. Must be a positive number.
-
opacity
path.opacity
A number representing the opacity of the path. Use strictly for setting. Must be a number 0-1.
-
cap
path.cap
A string representing the type of stroke cap to render. All applicable values can be found on the w3c spec. Defaults to
"round"
. -
join
path.join
A string representing the type of stroke join to render. All applicable values can be found on the w3c spec. Defaults to
"round"
. -
miter
path.miter
A number representing the miter limit for the stroke. Defaults to 1.
-
rotation
path.rotation
A number that represents the rotation of the path in the drawing space, in radians.
-
scale
path.scale
A number that represents the uniform scale of the path in the drawing space.
-
translation
path.translation
A
Two.Vector
that represents x, y translation of the path in the drawing space. -
parent
path.parent
A reference to the
Two.Group
that contains this instance. -
vertices
path.vertices
A
Two.Utils.Collection
ofTwo.Anchor
s that is two-way databound. Individual vertices may be manipulated. -
closed
path.closed
Boolean that describes whether the path is closed or not.
-
curved
path.curved
Boolean that describes whether the path is curved or not.
-
automatic
path.automatic
Boolean that describes whether the path should automatically dictate how
Two.Anchor
s behave. This defaults totrue
. -
beginning
path.beginning
A number, 0-1, that is mapped to the layout and order of vertices. It represents which of the vertices from beginning to end should start the shape. Exceedingly helpful for animating strokes. Defaults to 0.
-
ending
path.ending
A number, 0-1, that is mapped to the layout and order of vertices. It represents which of the vertices from beginning to end should end the shape. Exceedingly helpful for animating strokes. Defaults to 1.
-
clip
path.clip
A boolean describing whether to render this shape as a clipping mask. This property is set automatically in correspondence with
Two.Group.mask
. Defaults tofalse
. -
clone
path.clone();
Returns a new instance of a
Two.Path
with the same settings. -
center
path.center();
Anchors all vertices around the centroid of the group.
-
addTo
path.addTo(group);
Adds the instance to a
Two.Group
. -
remove
path.remove();
If added to a
two.scene
this method removes itself from it. -
getBoundingClientRect
path.getBoundingClientRect(shallow);
Returns an object with top, left, right, bottom, width, and height parameters representing the bounding box of the path. Pass
true
if you're interested in the shallow positioning, i.e in the space directly affecting the object and not where it is nested. -
noFill
path.noFill();
Removes the fill.
-
noStroke
path.noStroke();
Removes the stroke.
-
plot
path.plot();
If curved goes through the vertices and calculates the curve. If not, then goes through the vertices and calculates the lines.
-
subdivide
path.subdivide();
Creates a new set of vertices that are
lineTo
anchors. For previously straight lines the anchors remain the same. For curved lines, however,Two.Utils.subdivide
is used to generate a new set of straight lines that are perceived as a curve. -
MakeObservable
Two.Path.MakeObservable(obj);
Convenience method to make getter / setter properties specific to
Two.Path
. Two.Line
-
This is a class for creating a line in two.js. It inherits from
Two.Path
, so it has all the same properties and functions asTwo.Path
. -
construction
var line = new Two.Line(x1, y1, x2, y2);
A line takes two sets of
x
,y
coordinates.x1
,y1
to define the left endpoint andx2
,y2
to define the right endpoint. Two.Rectangle
-
This is a class for creating a rectangle in two.js. It inherits from
Two.Path
, so it has all the same properties and functions asTwo.Path
. -
construction
var rectangle = new Two.Rectangle(x, y, width, height);
A rectangle takes a set of
x
,y
coordinates as its origin (the center of the rectangle by default) andwidth
,height
parameters to define the width and height of the rectangle. Two.RoundedRectangle
-
This is a class for creating a rounded rectangle in two.js. It inherits from
Two.Path
, so it has all the same properties and functions asTwo.Path
. -
construction
var roundedRect = new Two.RoundedRectangle(x, y, width, height, radius);
A rounded rectangle takes a set of
x
,y
coordinates as its origin (the center of the rounded rectangle by default) andwidth
,height
parameters to define the width and height of the rectangle. Lastly, it takes an optionalradius
number representing the radius of the curve along the corner of the rectangle.radius
defaults to1/12
th the of the smaller value betweenwidth
,height
. Two.Ellipse
-
This is a class for creating an ellipse in two.js. It inherits from
Two.Path
, so it has all the same properties and functions asTwo.Path
. -
construction
var ellipse = new Two.Ellipse(x, y, width, height);
An ellipse takes a set of
x
,y
coordinates as its origin (the center of the ellipse by default) andwidth
,height
parameters to define the width and height of the ellipse.To construct a circle leave
height
empty and the height will default to the width. Two.Star
-
This is a class for creating a star in two.js. It inherits from
Two.Path
, so it has all the same properties and functions asTwo.Path
. -
construction
var star = new Two.Star(x, y, or, ir, sides);
A star takes a set of
x
,y
coordinates as its origin (the center of the star by default) andor
parameter to define the outer radius of the star. Optionally you can define anir
inner radius for the star andsides
for how many sides the star has. By default heir
is half theor
and there are 5sides
. Two.Polygon
-
This is a class for creating a polygon, symmetrically multi-sided shape, in two.js. It inherits from
Two.Path
, so it has all the same properties and functions asTwo.Path
. -
construction
var polygon = new Two.Polygon(x, y, radius, sides);
A polygon takes a set of
x
,y
coordinates as its origin (the center of the polygon by default) andradius
,sides
parameters to define the radius of the polygon and how many sides the polygon has. By default there are 3sides
, a triangle.Prior to two.js
v0.5.0
Two.Polygon
acted as the base drawing class. WhatTwo.Path
effectively is afterv0.5.0
. Two.Group
-
This is a container object for two.js — it can hold shapes as well as other groups. At a technical level it can be considered an empty transformation matrix. It is recommended to use
two.makeGroup()
in order to add groups to your instance oftwo
, but it's not necessary. Unless specified methods return their instance ofTwo.Group
for the purpose of chaining. -
construction
var group = new Two.Group();
If you are constructing groups this way instead of
two.makeGroup()
, then don't forget to add the group to the instance's scene,two.add(group)
. -
id
group.id
The id of the group. In the svg renderer this is the same number as the
id
attribute given to the corresponding node. i.e: ifgroup.id = 5
thendocument.querySelector('#two-' + group.id)
will return the corresponding node. -
stroke
group.stroke
A string representing the color for the stroke of all child shapes. Use strictly for setting. All valid css representations of color are accepted.
-
fill
group.fill
A string representing the color for the area of all child shapes. Use strictly for setting. All valid css representations of color are accepted.
-
linewidth
group.linewidth
A number representing the thickness of all child shapes' strokes. Use strictly for setting. Must be a positive number.
-
opacity
group.opacity
A number representing the opacity of all child shapes. Use strictly for setting. Must be a number 0-1.
-
cap
group.cap
A string representing the type of stroke cap to render for all child shapes. Use strictly for setting. All applicable values can be found on the w3c spec. Defaults to
"round"
. -
join
group.join
A string representing the type of stroke join to render for all child shapes. Use strictly for setting. All applicable values can be found on the w3c spec. Defaults to
"round"
. -
miter
group.miter
A number representing the miter limit for the stroke of all child objects. Use strictly for setting. Defaults to 1.
-
rotation
group.rotation
A number that represents the rotation of the group in the drawing space, in radians.
-
scale
group.scale
A number that represents the uniform scale of the group in the drawing space.
-
translation
group.translation
A
Two.Vector
that represents x, y translation of the group in the drawing space. -
children
group.children
A map of all the children of the group.
-
parent
group.parent
A reference to the
Two.Group
that contains this instance. -
mask
group.mask
A reference to the
Two.Path
that masks the content within the group. Automatically sets the referencedTwo.Path.clip
totrue
. -
clone
group.clone();
Returns a new instance of a
Two.Group
with the same settings.This will copy the children as well, which can be computationally expensive.
-
center
group.center();
Anchors all children around the centroid of the group.
-
addTo
group.addTo(group);
Adds the instance to a
Two.Group
. In many ways the inverse oftwo.add(object)
. -
add
group.add(objects);
Add one or many shapes / groups to the instance. Objects can be added as arguments,
two.add(o1, o2, oN)
, or as an array depicted above. -
remove
group.remove(objects);
Remove one or many shapes / groups to the instance. Objects can be removed as arguments,
two.remove(o1, o2, oN)
, or as an array depicted above. -
getBoundingClientRect
group.getBoundingClientRect(shallow);
Returns an object with top, left, right, bottom, width, and height parameters representing the bounding box of the path. Pass
true
if you're interested in the shallow positioning, i.e in the space directly affecting the object and not where it is nested. -
noFill
group.noFill();
Remove the fill from all children of the group.
-
noStroke
group.noStroke();
Remove the stroke from all children of the group.
-
MakeObservable
Two.Group.MakeObservable(obj);
Convenience method to make getter / setter properties specific to
Two.Group
. Two.Vector
-
This is the atomic coordinate representation for two.js. A
Two.Vector
is different and specific to two.js because its main properties,x
andy
, trigger events which allow the renderers to efficiently change only when they need to. Unless specified methods return their instance ofTwo.Vector
for the purpose of chaining. -
construction
var vector = new Two.Vector(x, y);
-
x
vector.x
The x value of the vector.
-
y
vector.y
The y value of the vector.
-
set
vector.set(x, y);
Set the
x
,y
properties of the vector to the argumentsx
,y
. -
copy
vector.copy(v);
Set the
x
,y
properties of the vector from another vector,v
. -
clear
vector.clear();
Set the
x
,y
properties of the vector to 0. -
clone
vector.clone();
Returns a new instance of a
Two.Vector
with the samex
,y
values as the instance. -
add
vector.add(v1, v2);
Add to vectors together. The sum of the
x
,y
values will be set to the instance. -
addSelf
vector.addSelf(v);
Add the
x
,y
values of the instance to the values of another vector. Set the sum to the instance's values. -
sub
vector.sub(v1, v2);
Subtract two vectors. Set the difference to the instance.
-
subSelf
vector.subSelf(v);
Subtract a vector,
v
, from the instance. -
multiplySelf
vector.multiplySelf(v);
Multiply the
x
,y
values of the instance by another vector's,v
,x
,y
values. -
multiplyScalar
vector.multiplyScalar(value);
Multiply the
x
,y
values of the instance by another number,value
. -
divideScalar
vector.divideScalar(value);
Divide the
x
,y
values of the instance by another number,value
. -
negate
vector.negate();
Toggle the sign of the instance's
x
,y
values. -
dot
vector.dot(v);
Return the dot product of the instance and a vector,
v
. -
lengthSquared
vector.lengthSquared();
Return the length of the vector squared.
-
length
vector.length();
Return the length of the vector.
-
normalize
vector.normalize();
Reduce the length of the vector to the unit circle.
-
distanceTo
vector.distanceTo(v);
Return the distance from the instance to another vector,
v
. -
distanceToSquared
vector.distanceToSquared(v);
Return the distance squared from the instance to another vector,
v
. -
setLength
vector.setLength(length);
Set the length of a vector to a specified distance,
length
. -
equals
vector.equals(v);
Return a boolean representing whether or not the vectors are within 0.0001 of each other. This fuzzy equality helps with Physics libraries.
-
lerp
vector.lerp(v, t);
Linear interpolation of the instance's current
x
,y
values to the destination vector,v
, by an amount,t
. Where t is a value 0-1. -
isZero
vector.isZero();
Returns a boolean describing the length of the vector less than 0.0001.
Two.Anchor
-
Taken from the Adobe Illustrator nomenclature a
Two.Anchor
represents an anchor point in two.js. This class delineates to the renderer what action to take when plotting points. It inherits all properties and methods fromTwo.Vector
. As a result,Two.Anchor
can be used as such. Depending on its command, anchor points may or may not have corresponding control points to describe how their bezier curves should be rendered. -
construction
var anchor = new Two.Anchor(x, y, lx, ly, rx, ry, command);
A
Two.Anchor
can take initial positions ofx
andy
to orient the point.lx
andly
describe where the left control point will reside. Likewiserx
andry
describe where the right control point will reside. Finally, thecommand
describes what action the renderer will take once rendering. A more detailed description of commands can be found on the w3c and the available commands in two.js can be found underTwo.Commands
.Two.Anchor
is introduced to two.js as of v0.3.0 -
x
anchor.x
The x value of the anchor's position.
-
y
anchor.y
The y value of the anchor's position.
-
command
anchor.command
The command for the given anchor.
-
controls
anchor.controls
An object that exists only when
anchor.command
isTwo.Commands.curve
. It holds the anchor's control pointTwo.Vector
s and describes what the make up of the curve will be.-
right
anchor.controls.right
A
Two.Vector
that represents the position of the control point to the “right” of the anchor's position. To further clarify, if you were to orient the anchor so that it was normalized and facing up, this control point would be to the right of it. -
left
anchor.controls.left
A
Two.Vector
that represents the position of the control point to the “left” of the anchor's position. To further clarify, if you were to orient the anchor so that it was normalized and facing up, this control point would be to the left of it.
-
-
clone
anchor.clone();
Returns a new instance of a
Two.Anchor
with the samex
,y
,controls
, andcommand
values as the instance. -
listen
anchor.listen();
Convenience method to add event bubbling to an attached path.
-
ignore
anchor.ignore();
Convenience method to remove event bubbling to an attached path.
-
AppendCurveProperties
Anchor.AppendCurveProperties();
Convenience method to add the
controls
object. Two.Stop
-
This is a class for defining how gradients are colored in two.js. By itself a
Two.Stop
doesn't render anything specifically to the screen. -
construction
var stop = new Two.Stop(offset, color, opacity);
A stop takes a
0
to1
offset value which defines where on the trajectory of the gradient the full color is rendered. It also takes acolor
which is acss
string representing the color value and an optionalopacity
which is also a0
to1
value. -
offset
stop.offset
A
0
to1
offset value which defines where on the trajectory of the gradient the full color is rendered. -
color
stop.color
A
css
string that represents the color of the stop. -
opacity
stop.opacity
A
0
to1
value which defines the opacity of the stop.This only renders in the
Two.Types.svg
mode. -
clone
stop.clone();
Clones a
stop
. Returns a newTwo.Stop
. Two.LinearGradient
-
This is a class for creating a LinearGradient in two.js. By itself a
Two.LinearGradient
doesn't render anything specifically to the screen. However, in conjunction with aTwo.Path
you can styleTwo.Path.fill
orTwo.Path.stroke
with aTwo.LinearGradient
to render a gradient for that part of theTwo.Path
. Check the examples page for exact usage. -
construction
var linearGradient = new Two.LinearGradient(x1, y1, x2, y2, stops);
A linear gradient takes two sets of
x
,y
coordinates to define the endpoints of the styling. These coordinates are relative to the origin of aTwo.Path
. This typically means you'll want to go from a negative quadrant to a positive quadrant in order for the gradient to render correctly. Lastly it takes an array ofTwo.Stop
s which represent the color value along the gradient's trajectory. -
left
linearGradient.left
A
Two.Vector
that represents the position of thex
,y
coordinates to the “left” of the gradient's two end points. -
right
linearGradient.right
A
Two.Vector
that represents the position of thex
,y
coordinates to the “right” of the gradient's two end points. -
spread
linearGradient.spread
Defines how the gradient is rendered by the renderer. For more details see the w3c
svg
spec. -
stops
linearGradient.stops
A
Two.Utils.Collection
ofTwo.Stop
s that is two-way databound. Individual stops may be manipulated. -
clone
linearGradient.clone();
A function to clone a
linearGradient
. Also, clones eachTwo.Stop
in thelinearGradient.stops
array. Two.RadialGradient
-
This is a class for creating a RadialGradient in two.js. By itself a
Two.RadialGradient
doesn't render anything specifically to the screen. However, in conjunction with aTwo.Path
you can styleTwo.Path.fill
orTwo.Path.stroke
with aTwo.RadialGradient
to render a gradient for that part of theTwo.Path
. Check the examples page for exact usage. -
construction
var radialGradient = new Two.radialGradient(x, y, radius, stops, fx, fy);
A radial gradient takes a set of
x
,y
coordinates to define the center of the styling. These coordinates are relative to the origin of aTwo.Path
. This typically means you'll want to set these to0
,0
. Next define how large theradius
for the radial gradient is. Lastly, pass an array ofTwo.Stop
s to define the coloring of the radial gradient. Optionally, you can pass a set ofx
,y
coordinates to define the focal position of the radial gradient's trajectory. -
center
radialGradient.center
A
Two.Vector
that represents the position of thex
,y
coordinates at the center of the gradient. -
radius
radialGradient.radius
A number representing the radius of the
radialGradient
. -
focal
linearGradient.focal
A
Two.Vector
that represents the position of thex
,y
coordinates as the focal point for the gradient's trajectory. -
spread
radialGradient.spread
Defines how the gradient is rendered by the renderer. For more details see the w3c
svg
spec. -
stops
radialGradient.stops
A
Two.Utils.Collection
ofTwo.Stop
s that is two-way databound. Individual stops may be manipulated. -
clone
radialGradient.clone();
A function to clone a
radialGradient
. Also, clones eachTwo.Stop
in theradialGradient.stops
array. Two.Text
-
This is a class for creating, manipulating, and rendering text dynamically in Two.js. As such it is rather primitive. You can use custom fonts through @Font Face spec. However, you do not have control over the glyphs themselves. If you'd like to mainpulate that specifically it is recommended to use SVG Interpreter. A text object extends
Two.Shape
. -
construction
var text = new Two.Text(message, x, y, styles);
A text object takes in a
message
, the string representation of what will be displayed. It then takes anx
andy
number where the text object will be placed in the group. Finally, an optionalstyles
object to apply any other additional styles. Applicable properties to affect can be found inTwo.Text.Properties
. -
value
text.value
A string representing the text that will be rendered to the stage.
-
family
text.family
A string representing the
css font-family
to be applied to the rendered text. Default value is'sans-serif'
. -
size
text.size
A number representing the text's size to be applied to the rendered text. Default value is
13
. -
leading
text.leading
A number representing the leading, a.k.a. line-height, to be applied to the rendered text. Default value is
17
. -
alignment
text.alignment
A string representing the horizontal alignment to be applied to the rendered text. e.g:
'left'
,'right'
, or'center'
. Default value is'middle'
. -
fill
text.fill
A string representing the color for the text area to be filled. All valid css representations of color are accepted. Default value is
'#000'
. -
stroke
text.stroke
A string representing the color for the text area to be stroked. All valid css representations of color are accepted. Default value is
'transparent'
. -
linewidth
text.linewidth
A number representing the linewidth to be applied to the rendered text. Default value is
1
. -
style
text.style
A string representing the font style to be applied to the rendered text. e.g:
'normal'
or'italic'
. Default value is'normal'
. -
weight
text.weight
A number or string representing the weight to be applied to the rendered text. e.g:
500
or'normal'
. For more information see the Font Weight Specification. Default value is500
. -
decoration
text.decoration
A string representing the text decoration to be applied to the rendered text. e.g:
'none'
,'underline'
, or'strikethrough'
. Default value is'none'
-
baseline
text.baseline
A string representing the vertical aligment to be applied to the rendered text. e.g:
'middle'
,'baseline'
, or'top'
. Default value is'middle'
. -
opacity
text.opacity
A number representing the opacity of the path. Use strictly for setting. Must be a number 0-1.
-
visible
text.visible
A boolean representing whether the text object is visible or not.
-
rotation
text.rotation
A number that represents the rotation of the text in the drawing space, in radians.
-
scale
text.scale
A number that represents the uniform scale of the text in the drawing space.
-
translation
text.translation
A
Two.Vector
that represents x, y translation of the text in the drawing space. -
clone
text.clone();
Returns a new instance of a
Two.Text
with the same settings. -
getBoundingClientRect
text.getBoundingClientRect(shallow);
Currently returns an empty object. A shim for compatibility with matrix math in the various renderers.
-
noFill
text.noFill();
Removes the fill.
-
noStroke
text.noStroke();
Removes the stroke.
-
MakeObservable
Two.Text.MakeObservable(obj);
Convenience method to make getter / setter properties specific to
Two.Text
.
These are the main classes that a typical developer will come across with when using two.js, however the project is built with a few more classes behind the scene. If you're interested in the nitty-gritty then it's recommended to check out the source.
Credits
Two.js is not possible without these great contributions to JavaScript:
-
Underscore.js
Utility functions and the magical
debounce
method which makes much of the morphing efficient. -
Backbone.js
Event binding, bubbling, and communication.
-
Request Animation Frame
Polyfill version by Paul Irish.
-
Three.js
The initial proof-of-concept was made in Three.js — much of the style and tone of the API mimics Three.
-
Qunit + Resemble + Canvas2Blob
Testing framework with image differencing functions for cross rendering comparisons.
-
Code Mirror + jQuery
Simple in-browser editor for tweaking values in Basic Usage.
-
Tween.js
Awesome tween library in JavaScript.
-
Bourbon
Simple SCSS framework for writing better css.
-
Google Data Arts Team
Inspiring JavaScript developers everywhere.