Quantcast
Channel: Hacker News 50
Viewing all articles
Browse latest Browse all 9433

Two.js

$
0
0

Comments:"Two.js"

URL:http://jonobr1.github.io/two.js


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.

Development Version
Uncompressed with comments about 128kb

Production Version
Minified using Closure Compiler about 50kb

Two.js requires Underscore.js and Backbone.jsEvents. 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.

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!

  • 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 the Two class. Unless specified methods return their instance of Two for the purpose of chaining.
  • constructionvar two = new Two(params);

    Create a new instance of Two where params is a JavaScript object with several optional parameters listed below:

    • typeparams.type

      Set the type of renderer for the instance: svg, webgl, canvas, etc.. Applicable types are carried within Two.Types. Default type is Two.Types.svg.

    • widthparams.width

      Set the width of the drawing space. Disregarded if params.fullscreen is set to true. Default width is 640 pixels.

    • heightparams.height

      Set the height of the drawing space. Disregarded if params.fullscreen is set to true. Default height is 480 pixels.

    • autostartparams.autostart

      A boolean to automatically add the instance to draw on requestAnimationFrame. This is a convenient substitute so you don't have to call two.play().

    • fullscreenparams.fullscreen

      A boolean to set the drawing space of the instance to be fullscreen or not. If set to true then width and height parameters will not be respected.

  • typetwo.type

    A string representing which type of renderer the instance has implored.

  • frameCounttwo.frameCount

    A number representing how many frames have elapsed.

  • widthtwo.width

    The width of the instance's dom element.

  • heighttwo.height

    The height of the instance's dom element.

  • playingtwo.playing

    A boolean representing whether or not the instance is being updated through the automatic requestAnimationFrame.

  • renderertwo.renderer

    The instantiated rendering class for the instance. For a list of possible rendering types check out Two.Types.

  • scenetwo.scene

    The base level Two.Group which houses all objects for the instance. Because it is a Two.Group transformations can be applied to it that will affect all objects in the instance. This is handy as a makeshift camera.

  • appendTotwo.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.

  • playtwo.play();

    This method adds the instance to the requestAnimationFrame loop. In affect enabling animation for this instance.

  • pausetwo.pause();

    This method removes the instance from the requestAnimationFrame loop. In affect halting animation for this instance.

  • updatetwo.update();

    This method updates the dimensions of the drawing space, increments the tick for animation, and finally calls two.render(). When using the built-in requestAnimationFrame hook, two.play(), this method is invoked for you automatically.

  • rendertwo.render();

    This method makes the instance's renderer draw. It should be unnecessary to inoke this yourself at anytime.

  • addtwo.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.

  • makeLinetwo.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 and x2, y2 are the x, y values for the second coordinate. It returns a Two.Polygon object.

  • makeRectangletwo.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 and width, height represents the width and height of the rectangle. It returns a Two.Polygon object.

  • makeCircletwo.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 and radius is the radius of the circle. It returns a Two.Polygon object.

  • makeEllipsetwo.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 and width, height are the dimensions of the ellipse. It returns a Two.Polygon object.

  • makeCurvetwo.makeCurve(x1, y1, x2, y2, xN, yN, open);

    Draws a curved polygon to the instance's drawing space. The arguments are a little tricky. It returns a Two.Polygon 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. If true 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 of Two.Vector'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 points Two.Vector's.

  • makePolygontwo.makePolygon(x1, y1, x2, y2, xN, yN, open);

    Draws a polygon to the instance's drawing space. The arguments are a little tricky. It returns a Two.Polygon 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. If true the polygon will have two clear endpoints, otherwise it will be closed.

    This method also recognizes the format two.makePolygon(points, open) where points is an array of Two.Vector'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 points Two.Vector's.

    The Two.Polygon that this method creates is the base shape for all of the make functions.

  • makeGrouptwo.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.Polygons or Two.Groups. As well as a list of objects as the arguments, two.makeGroup(o1, o2, oN). It returns a Two.Group object.

  • interprettwo.interpret(svgNode);

    Reads an svg node and draws the svg object by creating Two.Polygons and Two.Groups from the reference. It then adds it to the instance's drawing space. It returns an Two.Group object.

    At the time of writing, two.interpret accepts compound paths, but often has unexpected results. Therefore it is recommended to break apart and Release Compound Paths as much as possible.

  • bindtwo.bind(event, callback);

    Bind an event, string, to a callback function. Passing "all" will bind the callback to all events. Inherited from Backbone.js.

  • unbindtwo.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.

  • ArrayTwo.Array

    A JavaScript Float32Array with graceful fallback to JavaScript Array.

  • TypesTwo.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, and webgl. e.g: Two.Types.svg

  • PropertiesTwo.Properties

    A list of renderer specific application properties.

  • EventsTwo.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 and resize when the dimensions of the drawing space change. Related to two.bind and two.trigger.

  • ResolutionTwo.Resolution

    A number representing how many subdivisions should be present during curve calculations.

  • InstancesTwo.Instances

    A running list of all instances created on the page.

  • noConflictTwo.noConflict();

    Run two.js in noConflict mode, returning the two variable to its previous owner. Returns a reference to the Two class.

  • UtilsTwo.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.

  • ErrorTwo.Error(message);

    A two.js specific custom error handler. Takes a message, string, to display in the console to developers.

  • Two.Polygon

  • This is the base class for creating all drawable shapes in two.js. Unless specified methods return their instance of Two.Polygon for the purpose of chaining.
  • constructionvar polygon = new Two.Polygon(vertices, closed, curved);

    A polygon takes an array of vertices which are made up of Two.Vectors. This is essential for the two-way databinding. It then takes two booleans, closed and curved which delineate whether the shape should be closed (lacking endpoints) and whether the shape should calculate curves or straight lines between the vertices.

    If you are constructing groups this way instead of two.makePolygon(), then don't forget to add the group to the instance's scene, two.add(group).

  • idpolygon.id

    The id of the polygon. In the svg renderer this is the same number as the id attribute given to the corresponding node. i.e: if polygon.id = 4 then document.querySelector('two-' + group.id) will return the corresponding svg node.

  • strokepolygon.stroke

    A string representing the color for the stroke of the polygon. All valid css representations of color are accepted.

  • fillpolygon.fill

    A string representing the color for the area of the vertices. All valid css representations of color are accepted.

  • linewidthpolygon.linewidth

    A number representing the thickness the polygon's strokes. Must be a positive number.

  • opacitypolygon.opacity

    A number representing the opacity of the polygon. Use strictly for setting. Must be a number 0-1.

  • cappolygon.cap

    A string representing the type of stroke cap to render. All applicable values can be found on the w3c spec. Defaults to "round".

  • joinpolygon.join

    A string representing the type of stroke join to render. All applicable values can be found on the w3c spec. Defaults to "round".

  • miterpolygon.miter

    A number representing the miter limit for the stroke. Defaults to 1.

  • rotationpolygon.rotation

    A number that represents the rotation of the polygon in the drawing space, in radians.

  • scalepolygon.scale

    A number that represents the uniform scale of the polygon in the drawing space.

  • translationpolygon.translation

    A Two.Vector that represents x, y translation of the polygon in the drawing space.

  • parentpolygon.parent

    A reference to the Two.Group that contains this instance.

  • verticespolygon.vertices

    An array of Two.Vectors that is two-way databound. Individual vertices may be manipulated, however it is imperative that the array itself does not get manipulated.

  • closedpolygon.closed

    Boolean that describes whether the polygon is closed or not.

  • curvedpolygon.curved

    Boolean that describes whether the polygon is curved or not.

  • beginningpolygon.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.

  • endingpolygon.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.

  • clonepolygon.clone();

    Returns a new instance of a Two.Polygon with the same settings.

  • centerpolygon.center();

    Anchors all vertices around the centroid of the group.

  • addTopolygon.addTo(group);

    Adds the instance to a Two.Group.

  • removegroup.remove(objects);

    If added to a two.scene this method removes itself from it.

  • getBoundingClientRectpolygon.getBoundingClientRect();

    Returns an object with top, left, right, bottom, width, and height parameters representing the bounding box of the polygon.

  • noFillpolygon.noFill();

    Removes the fill.

  • noStrokepolygon.noStroke();

    Removes the stroke.

  • 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 of two, but it's not necessary. Unless specified methods return their instance of Two.Group for the purpose of chaining.
  • constructionvar 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).

  • idgroup.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: if group.id = 5 then document.querySelector('two-' + group.id) will return the corresponding node.

  • strokegroup.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.

  • fillgroup.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.

  • linewidthgroup.linewidth

    A number representing the thickness of all child shapes' strokes. Use strictly for setting. Must be a positive number.

  • opacitygroup.opacity

    A number representing the opacity of all child shapes. Use strictly for setting. Must be a number 0-1.

  • capgroup.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".

  • joingroup.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".

  • mitergroup.miter

    A number representing the miter limit for the stroke of all child objects. Use strictly for setting. Defaults to 1.

  • rotationgroup.rotation

    A number that represents the rotation of the group in the drawing space, in radians.

  • scalegroup.scale

    A number that represents the uniform scale of the group in the drawing space.

  • translationgroup.translation

    A Two.Vector that represents x, y translation of the group in the drawing space.

  • childrengroup.children

    A map of all the children of the group.

  • parentgroup.parent

    A reference to the Two.Group that contains this instance.

  • clonegroup.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.

  • centergroup.center();

    Anchors all children around the centroid of the group.

  • addTogroup.addTo(group);

    Adds the instance to a Two.Group. In many ways the inverse of two.add(object).

  • addgroup.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.

  • removegroup.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.

  • getBoundingClientRectgroup.getBoundingClientRect();

    Returns an object with top, left, right, bottom, width, and height parameters representing the bounding box of the group.

  • noFillgroup.noFill();

    Remove the fill from all children of the group.

  • noStrokegroup.noStroke();

    Remove the stroke from all children of the group.

  • MakeGetterSetterGroup.MakeGetterSetter();

    Convenience method to turn a property into an EcmaScript 5 getter / setter.

  • 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 and y, trigger events which allow the renderers to efficiently change only when they need to. Unless specified methods return their instance of Two.Vector for the purpose of chaining.
  • constructionvar vector = new Two.Vector(x, y);

  • xvector.x

    The x value of the vector.

  • yvector.y

    The y value of the vector.

  • setvector.set(x, y);

    Set the x, y properties of the vector to the arguments x, y.

  • copyvector.copy(v);

    Set the x, y properties of the vector from another vector, v.

  • clearvector.clear();

    Set the x, y properties of the vector to 0.

  • clonevector.clone();

    Returns a new instance of a Two.Vector with the same x, y values as the instance.

  • addvector.add(v1, v2);

    Add to vectors together. The sum of the x, y values will be set to the instance.

  • addSelfvector.addSelf(v);

    Add the x, y values of the instance to the values of another vector. Set the sum to the instance's values.

  • subvector.sub(v1, v2);

    Subtract two vectors. Set the difference to the instance.

  • subSelfvector.subSelf(v);

    Subtract a vector, v, from the instance.

  • multiplySelfvector.multiplySelf(v);

    Multiply the x, y values of the instance by another vector's, v, x, y values.

  • multiplyScalarvector.multiplyScalar(value);

    Multiply the x, y values of the instance by another number, value.

  • divideScalarvector.divideScalar(value);

    Divide the x, y values of the instance by another number, value.

  • negatevector.negate();

    Toggle the sign of the instance's x, y values.

  • dotvector.dot(v);

    Return the dot product of the instance and a vector, v.

  • lengthSquaredvector.lengthSquared();

    Return the length of the vector squared.

  • lengthvector.length();

    Return the length of the vector.

  • normalizevector.normalize();

    Reduce the length of the vector to the unit circle.

  • distanceTovector.distanceTo(v);

    Return the distance from the instance to another vector, v.

  • distanceToSquaredvector.distanceToSquared(v);

    Return the distance squared from the instance to another vector, v.

  • setLengthvector.setLength(length);

    Set the length of a vector to a specified distance, length.

  • equalsvector.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.

  • lerpvector.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.

  • isZerovector.isZero();

    Returns a boolean describing the length of the vector less than 0.0001.

  • These are the four 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.

    Two.js is not possible without these great contributions to JavaScript:


    Viewing all articles
    Browse latest Browse all 9433

    Trending Articles