StageJS

2D HTML5 rendering and layout engine for game development

README

Stage

Stage.js is a 2D HTML5 JavaScript library for cross-platform game development, it is lightweight, fast and open-source.

[Check out examples and demos!](http://piqnt.com/stage.js/)



Introduction


Canvas is the graphic component of HTML5 game development, but it only has a drawing API and there is no data model like the DOM to compose your application.
You need to manually draw your application and manage rendering cycles to play it.
Moreover, mouse events are only available at the entire Canvas level and they also need to be processed manually.

Stage.js provides a DOM-like tree data model to compose your application and internally manages rendering cycles and the drawing of your application.
It also processes and distributes mouse and touch events to targeted tree nodes.
A Stage.js application consists of a tree of nodes. Each node is pinned (transformed) against its parent and has zero, one or more image textures.

Each rendering cycle consists of ticking and drawing tree nodes. On ticking, nodes adjust themselves to recent updates while on drawing each node transforms according to its pinning and draws its textures.

Rendering is retained and is paused when there is no change.

Example


  1. ```js
  2. // Create new app
  3. Stage(function(stage) {

  4.   // Set view box
  5.   stage.viewbox(300, 200);

  6.   // Create an image and append it to stage
  7.   var box = Stage.image('box').appendTo(stage);

  8.   // Align box to center
  9.   box.pin('align', 0.5);

  10.   // On mouse click...
  11.   box.on('click', function(point) {
  12.     // ...tween scale values of this node
  13.     this.tween().ease('bounce').pin({
  14.       scaleX : Math.random() + 0.5,
  15.       scaleY : Math.random() + 0.5
  16.     });
  17.   });
  18. });

  19. // Adding a texture
  20. Stage({
  21.   image : 'sample.png',
  22.   textures : {
  23.     box : { x : 0, y : 0, width : 30, height : 30 }
  24.   }
  25. });
  26. ```


Installation


Download

Latest builds are available in the project releases page.

NPM


  1. ```
  2. npm install stage-js --save
  3. ```

Bower


  1. ```
  2. bower install stage-js --save
  3. ```


Usage


Browser


Include an appropriate build file from dist directory in your HTML page before your application. For example:

  1. ```html
  2. <script src="path/to/stage.web.min.js"></script>
  3. <script src="path/to/your-app.js"></script>
  4. ```

Browserify, CommonJS, Node.js

Generally it is preferred to directly include a browser build file in HTML pages, however it is also possible to use CommonJS require instead, for example:

  1. ```js
  2. var Stage = require('stage-js/platform/web');
  3. ```

See platform directory for other available modules.


Resources


Introduction to Stage.js  by Baljeet Rathi, SitePoint

中文手册  by Villor 紫刃


API Doc


Application

An application is created by passing a callback function to Stage().
The library will load, create and initialize all required components and will then call the provided function with the application root node and display the container which is normally a Canvas element.

  1. ```javascript
  2. // Create and start an application
  3. Stage(function(stage, display) {

  4.   // Set viewbox for stage, see pinning for valid modes
  5.   stage.viewbox(width, height, mode = 'in-pad');

  6.   // Listen to view port resize events
  7.   stage.on('viewport', function(viewport) {
  8.     // `viewport` attributes are `width`, `height` and `ratio`
  9.   });

  10.   // Pause playing
  11.   stage.pause();

  12.   // Resume playing
  13.   stage.resume();
  14. });
  15. ```


Tree Model

Every app consists of a tree. The tree's root is provided as stage.

  1. ```javascript
  2. // Create a new node instance (with no textures)
  3. var node = Stage.create();

  4. // Append/prepend child to parent's children (accepts array)
  5. parent.append(child);
  6. parent.prepend(child);

  7. // Append/prepend child to parent's children
  8. child.appendTo(parent);
  9. child.prependTo(parent);

  10. // Insert sibling after/before child (accepts array)
  11. child.insertNext(sibling);
  12. child.insertPrev(sibling);

  13. // Insert sibling after/before child
  14. sibling.insertAfter(child);
  15. sibling.insertBefore(child);

  16. // Remove child from its parent
  17. child.remove();

  18. // Remove child from parent (accepts array)
  19. parent.remove(child);

  20. // Remove all of parent's children
  21. parent.empty();

  22. // Get parent's first/last (visible) child
  23. parent.first(onlyVisible = false);
  24. parent.last(onlyVisible = false);

  25. // Get immediate parent
  26. child.parent();

  27. // Get child's next/prev (visible) sibling
  28. child.next(onlyVisible = false);
  29. child.prev(onlyVisible = false);

  30. // Get node's visiblity
  31. node.visible();
  32. // Set node's visiblity
  33. node.visible(visible);
  34. node.hide();
  35. node.show();

  36. // Iterate over parent's children, child can not be removed
  37. for (var child = parent.first(); child; child = child.next()) {
  38.   // use child
  39. }

  40. // Iterate over parent's children, child can be removed
  41. var child, next = parent.first();
  42. while (child = next) {
  43.   next = child.next();
  44.   // use child
  45. }

  46. // Visit node's sub-tree including node itself
  47. node.visit({
  48.   start : function(node) {
  49.     return skipChildren;
  50.   },
  51.   end : function(node) {
  52.     return stopVisit;
  53.   },
  54.   reverse : reverseChildrenOrder = false,
  55.   visible : onlyVisibleNodes = false
  56. });
  57. ```


Game Loop

Each rendering cycle consists of ticking and redrawing the application tree.
Application and its nodes can be updated during ticking.
Depending on application activities there can be three different follow-ups after ticking:

If at least one node is touched then the entire application tree will be redrawn and the game loop will continue.
If no node is touched but at least one ticking function returns true then the game loop will continue but the previous drawing will be retained.
If no node is touched and no ticking function returns true then the application will pause until it is touched directly or indirectly.

Nodes can be touched directly by calling node.touch() but usually they are touched indirectly by other actions such as pinning or tree manipulation.

  1. ```javascript
  2. // Register a function to be called on ticking
  3. node.tick(function(millisecElapsed) {
  4.   return continueGameLoop;
  5. }, beforeChildren = false);

  6. // Touch node
  7. node.touch();
  8. ```


Pinning

Pinning specifies how a node is attached to its parent.
Pinning consists of size, transformation, positioning and transparency.

  1. ```javascript
  2. // Get a pinning value
  3. node.pin(name);

  4. // Set a pinning value
  5. node.pin(name, value);

  6. // Set one or more pinning values
  7. node.pin({
  8.   name : value,
  9.   ...
  10. });
  11. ```

When nameX equals nameY, name shorthand can be used instead.

Size

For some nodes, such as images, strings, rows and columns, size is set automatically.

  1. ```javascript
  2. node.pin({
  3.   height : height,
  4.   width : width
  5. });

  6. // Shortcut for setting size:
  7. node.size(width, height);
  8. node.width(width);
  9. node.height(height);

  10. // Shortcut for getting size:
  11. node.width();
  12. node.height();
  13. ```

Transformation

Transformation consists of scaling, skewing and rotating. Rotation is applied after scaling and skewing.

  1. ```javascript
  2. node.pin({
  3.   scaleX : 1,
  4.   scaleY : 1,
  5.   skewX : 0,
  6.   skewY : 0,
  7.   rotation : 0
  8. });

  9. // Shortcut for setting transformation:
  10. node.scale(x, y = x);
  11. node.scale({ x : x, y : y });
  12. node.skew(x, y = x);
  13. node.skew({ x : x, y : y });
  14. node.rotate(angle);
  15. ```

Positioning

When positioning, handle point on self is positioned at offset distance from align point on the parent.
Handle and align are defined as a ratio of width/height, 0 is top/left and 1 is bottom/right.
Handle defaults to the align value when it is not specified.

  1. ```javascript
  2. node.pin({
  3.   alignX : 0,
  4.   alignY : 0,
  5.   handleX : 0,
  6.   handleY : 0,
  7.   offsetX : 0,
  8.   offsetY : 0
  9. });

  10. // Shortcut methods for setting positioning:
  11. node.offset(x, y);
  12. node.offset({ x : x, y : y });
  13. ```

By default an axis-aligned bounding box (AABB) after transformation is used for positioning,
however it is possible to use a non-transformed box by setting a pivot location.
Pivot location is defined as ratio of non-transformed width/height and is used as central point on self for scale, skew and rotation.

  1. ```javascript
  2. node.pin({
  3.   pivotX : 0,
  4.   pivotY : 0
  5. });
  6. ```

Transparency

Transparency can be applied to both node textures and subtree nodes or only node textures.

  1. ```javascript
  2. node.pin({
  3.   alpha : 1,
  4.   textureAlpha : 1
  5. });

  6. // Shortcut methods for setting transparency:
  7. node.alpha(alpha);
  8. node.alpha(alpha, textureAlpha);
  9. ```

Scale To

Scale to a new width/height, if mode is set to scale proportionally. Valid modes are:
- in: maximum scale which keeps node edges inside the scaleWidth/Height
- in-pad: like in, but evenly pads node to fill the entire scaleWidth/Height
- out: minimum scale which keeps node edges outside scaleWidth/Height
- out-crop: like out, but evenly crops it to scaleWidth/Height

  1. ```javascript
  2. node.pin({
  3.   scaleMode : mode,
  4.   scaleWidth : width,
  5.   scaleHeight : height
  6. });

  7. // Shortcut method:
  8. node.scaleTo(width, height, mode);
  9. ```


Events

Event listeners can be registered and unregistered to nodes, listeners are called when an event is published to a node.
Some events may be published to multiple nodes, but events do not propagate.

  1. ```javascript
  2. // Register a listener to node
  3. // Event `name` can be one or an array of strings or spaced separated strings
  4. node.on(name, listener);

  5. // Unregister a listener from node.
  6. node.off(name, listener);

  7. // Get listeners registered to node
  8. // Returns an array or undefined
  9. node.listeners(name);

  10. // Call listeners with args
  11. // Returns number of listeners called
  12. node.publish(name, args);
  13. ```


Mouse and Touch

Native mouse and touch events are captured, processed and published to application nodes.
Nodes receive mouse events in local coordinates, i.e. mouse location is specified as the distance to the top-left of the node.

  1. ```javascript
  2. // Add click listener to node
  3. node.on('click', function(point) {
  4.   // point.x and point.y are relative to this node left and top
  5.   // point.raw is original event
  6. });
  7. ```

Instead of native click events, syntatic click events are created and published to nodes.
In addition to standard event types, a syntactic mousecancel event type is also supported which is similar to touchcancel but is published when a mousedown is not followed by mouseup.

  1. ```javascript
  2. // Mouse events:
  3. Stage.Mouse.CLICK = 'click';
  4. Stage.Mouse.START = 'touchstart mousedown';
  5. Stage.Mouse.MOVE = 'touchmove mousemove';
  6. Stage.Mouse.END = 'touchend mouseup';
  7. Stage.Mouse.CANCEL = 'touchcancel mousecancel';
  8. ```


Texture

Textures are drawable objects which are used by tree nodes to draw graphics on the Canvas surface.

Texture Atlas

A texture atlas (sprite sheet) consists of a set of named textures which are referenced by name in an application.

Atlases are usually created using static image files. Images referenced in atlases are automatically preloaded.

  1. ```javascript
  2. // Adding texture atlas
  3. Stage({
  4.   name : 'mario', // optional
  5.   image : {
  6.     src : 'mario.png',
  7.     ratio : 1, // optional, for high-res images
  8.   }
  9.   textures : {
  10.     stand : { x : 0,   y : 0, width : 40, height : 60 },
  11.     walk : [
  12.       { x : 40,  y : 0, width : 40, height : 60 },
  13.       { x : 80,  y : 0, width : 40, height : 60 },
  14.       { x : 120, y : 0, width : 40, height : 60 }
  15.     ],
  16.     number : {
  17.       '0' : { x : 0,  y : 60, width : 10, height : 14 },
  18.       '1' : { x : 10, y : 60, width : 10, height : 14 },
  19.       '2' : { x : 20, y : 60, width : 10, height : 14 },
  20.       '3' : { x : 30, y : 60, width : 10, height : 14 },
  21.       '4' : { x : 40, y : 60, width : 10, height : 14 },
  22.       '5' : { x : 50, y : 60, width : 10, height : 14 },
  23.       '6' : { x : 60, y : 60, width : 10, height : 14 },
  24.       '7' : { x : 70, y : 60, width : 10, height : 14 },
  25.       '8' : { x : 80, y : 60, width : 10, height : 14 },
  26.       '9' : { x : 90, y : 60, width : 10, height : 14 }
  27.     }
  28.   }
  29. });

  30. Stage.image('mario:stand');

  31. Stage.anim('mario:walk').play();

  32. Stage.string('mario:number').value(100);
  33. ```

If image src starts with ./ it will be resolved relative to the current script URL.


Image

An image is a node with one texture.

  1. ```javascript
  2. // Create a new image instance
  3. var image = Stage.image(texture);

  4. // Change image texture
  5. image.image(texture);

  6. // Tile/Stretch image when pinning width and/or height
  7. // To define borders add top, bottom, left and right to texture
  8. image.tile();
  9. image.stretch();
  10. ```


Animation

An animation or anim is a node with an array of textures as frames.

  1. ```javascript
  2. // Create a new anim instance
  3. var anim = Stage.anim(textures, fps = 15);

  4. // Get or set animation frame-per-second
  5. anim.fps();
  6. anim.fps(fps);

  7. // Set animation frames, `textures` can be an array or a texture selector
  8. anim.frames(textures);

  9. // Go to n-th frame
  10. anim.gotoFrame(n);

  11. // Move n frames forward (or backward if n is negative)
  12. anim.moveFrame(n);

  13. // Get number of frames
  14. anim.length();

  15. // Start playing (from `frameName` if specified)
  16. anim.play(frameName = undefined);

  17. // Stop playing (and jump to `frameName` if specified)
  18. anim.stop(frameName = undefined);

  19. // Play `repeat * length` frames and then stop and call `callback`
  20. anim.repeat(repeat, callback = null);
  21. ```


String

String is a row of images which are dynamically selected from frames using characters of a string value (or items of an array value).

  1. ```javascript
  2. // Create a new string instance with frames
  3. var string = Stage.string(frames);

  4. // Set frames, a string referencing a map in an atlas
  5. string.frames("digits");

  6. // Set frames, a map with textures as values and frame names as keys
  7. string.frames({
  8.   '0' : zeroTexture,
  9.   '1' : oneTexture,
  10.   ...
  11. });

  12. // Set frames, a function which takes a char (or item) and returns a texture
  13. string.frames(function(char) {
  14.   // create a texture for char
  15.   return texture;
  16. });

  17. // Set value, it can be a string (or an array)
  18. // Characters (or items) are used to select frames and create a row of images
  19. string.value(value);

  20. // Get assigned value
  21. string.value();
  22. ```


Row and Column

A row/column is a node which organizes its children as a horizontal/vertical sequence.

  1. ```javascript
  2. // Create a new row/column
  3. var row = Stage.row(childrenAlignY = 0);
  4. var column = Stage.column(childrenAlignX = 0);

  5. // Make node a row/column
  6. node.row(childrenAlignY = 0);
  7. node.column(childrenAlignX = 0);

  8. // Add spacing between row/column cells
  9. node.spacing(space);
  10. ```


Box (experimental)

A box resizes to wrap its children. It can be applied to tiled/stretched
images to create variable size components such as windows and buttons.

  1. ```javascript
  2. // Create a new box
  3. var box = Stage.box();

  4. // Make node a box
  5. node = node.box();
  6. ```


Tweening

Tweening is used to apply smooth transitions to pinning values.

  1. ```javascript
  2. // Create a tweening entry
  3. // When `append` is true new entry is appended to current entries otherwise replaces them
  4. var tween = node.tween(duration = 400, delay = 0, append = false);

  5. // Set pinning values and start tweening
  6. // Pinning shortcut methods, such as `.scale()`, can also be used
  7. tween.pin(pinning);

  8. // Set easing for tweening, it can be either a function or an identifier
  9. // defined as 'name[-mode][(params)]', for example 'quad' or 'poly-in-out(3)'
  10. // Names: linear, quad, cubic, quart, quint, poly(p), sin/sine,
  11. //        exp, circle/circ, bounce, elastic(a, p), back(s)
  12. // Modes: in, out, in-out, out-in
  13. tween.ease(easing);

  14. // Set duration in milliseconds
  15. tween.duration(ms);

  16. // Set delay in milliseconds
  17. tween.delay(ms);

  18. // Callback when tweening is done
  19. tween.done(function() {
  20.   // this === node
  21. });

  22. // Remove this node when tweening ends
  23. tween.remove();

  24. // Hide this node when tweening ends
  25. tween.hide();

  26. // Create and chain a new tweening to this entry
  27. var nextTween = tween.tween(duration = 400, delay = 0);
  28. ```


Global Methods

  1. ```javascript

  2. // Create a new app
  3. Stage(function(stage, display) { });

  4. // Create and preload a texture atlas
  5. Stage({ });

  6. // A function to be called before starting any app
  7. // Can be used for preloading application assets
  8. Stage.preload(function(done) {
  9.   // Call `done` when loaded or failed
  10.   done(error);
  11. });

  12. // Pause playing all applications
  13. Stage.pause();

  14. // Resume playing all applications
  15. Stage.resume();
  16. ```


Development

To try examples with a live build run following command and check output for the URL to open in your browser:
  1. ```
  2. npm run dev
  3. ```


License

Copyright 2020 Ali Shakiba http://shakiba.me/stage.js  
Available under the MIT License