Spritejs Readthedocs Io en Latest
Spritejs Readthedocs Io en Latest
js Documentation
Release 1.2.1
Batiste Bieler
1 Download sprite.js 3
2 Examples 5
3 Table of content 7
3.1 How to use sprite.js? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2 Performance and different ways to draw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3 Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.4 Sprite.js API documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.5 Changelog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Index 23
i
ii
sprite.js Documentation, Release 1.2.1
Sprite.js is a framework that lets you create animations and games using sprites in an efficient way. The goal is to
allow a common framework for desktop and mobile browsers and use the latest technology available on each platform.
Sprite.js is tested on WebKit, Firefox, Android phones, Opera and IE9.
Contents 1
sprite.js Documentation, Release 1.2.1
2 Contents
CHAPTER 1
Download sprite.js
To download the latest version of sprite.js go to the Github repository or use the direct link to the library.
3
sprite.js Documentation, Release 1.2.1
Examples
To see examples of what the framework has to offer have a look at the test files.
5
sprite.js Documentation, Release 1.2.1
6 Chapter 2. Examples
CHAPTER 3
Table of content
// various transformations
sp.move(100, 100);
sp.rotate(3.14 / 4);
sp.scale(2);
sp.setOpacity(0.8);
sp.update();
});
7
sprite.js Documentation, Release 1.2.1
If you want a more interactive demonstration of basic sprite manipulation, there is a good example in the tests: http:
//batiste.github.io/sprite.js/tests/visual_guide.html
This library provides three rendering engines: HTML and canvas and WebGl. Please note that WebGl is still in an
experimental state.
By default the HTML engine is used. The HTML engine displays sprites using DOM elements, while the canvas
engine draw the sprites on the canvas. Each layer of the application can have a different engine. This enable you to
mix the two techniques if needed.
To make use of canvas with a layer you need to specify it in the options:
The canvas will be automaticaly cleared by the game ticker. If you don’t need it you can set the autoClear to false
when building a layer:
Performances with the particle test vary widely depending on the device, browser and platform:
Browsers Chrome linux Opera linux Firefox linux HTC Desire (webkit) IE9
HTML engine 2000 60 500 120 30
Canvas engine 1300 100 300 80 600
3.3 Troubleshooting
• When using canvas, I get an “Uncaught Error: INDEX_SIZE_ERR: DOM Exception 1” in updateCanvas*
This error appears when canvas try to read an image out of the boundary of the image itself. Check that your cycle
doesn’t go off the boundaries, and that the size and offset are correct.
For any other undocumented issue, please fill a bug on this page: https://github.com/batiste/sprite.js/issues
This documentation does not document all of Sprite.js features, but only those that are considered stable.
The scene object is a DOM container where all the Sprites will be drawn. You always need to start by creating a Scene
object.
class sjs.Scene(options)
Create a new Scene.
Options details:
Scene.options.parent
DOM parent of the scene. The default is document.body.
Scene.options.w
Width of the scene.
Scene.options.h
Height of the scene.
Scene.options.autoPause
Pause the scene when the user quit the current window. The default is true.
This is the list of the different methods available on the Scene object:
Scene.loadImages(images, callback)
Arguments
• images (Array) – An array of image sources.
• callback (function) – This gets called once all images are loaded.
Load the given array of image sources. When all images are loaded, the callback is executed.
Scene.reset()
Delete all layers present in this scene, delete the sprites and layers, and pause the ticker.
class Scene.Layer(name[, options ])
Create a Layer object, see the Layer section.
class Scene.Sprite([source, layer|options ])
Arguments
• source (string) – source of the image.
• layer (Layer) – the layer object.
• options (object) – options.
Create a Sprite object, see the Sprite section.
class Scene.Ticker(paint, options)
Arguments
• paint (function) – Gets called on every game tick. The ticker is passed as first para-
mater.
• options (object) – The possible options, see the Ticker section.
Create a Ticker object for this scene or reset the previous one.
class Scene.Cycle(triplets)
Arguments
• triplets (Array) – The triplets array.
Alias for sjs.Cycle, see the Cycle section.
class Scene.Input()
Alias for sjs.Input, see the Input section.
You can create the sprite using the Layer directly instead of the Scene:
You can also initialize any Sprite properties by passing an options object instead of the Layer object, eg:
All parameters are optional. If the layer is not specified, the default layer will be used. If you want to set the
layer but not any image you can do so like this:
Important methods
To update any visual changes to the view you should call the update method:
Sprite.update()
Apply the latest changes to the sprite’s layer.
Sprite.loadImg(source[, resetSize ])
Arguments
• source (string) – new image source.
• resetSize (boolean) – if true the size of the sprite will be reset by the new image.
Change the image sprite.
Sprite.remove()
Remove the DOM element if the HTML engine is used and enable the garbage collection of the object.
Sprite.canvasUpdate(layer)
Draw the sprite on a given Canvas layer. This doesn’t work with an HTML layer.
With a canvas engine, the surface will be automatically cleared before each game tick. You will need to call update to
draw the sprite on the canvas again. If you don’t want to do this you can set the layer autoClear attribute to false.
For technichal and performance reasons a Sprite’s attributes needs to be changed using a setters method. The following
attributes are READ ONLY:
Sprite.x
The horizontal position of the sprite as measured against the top left corner of the scene.
Sprite.y
The vertical position of the sprite as measured top left corder of the scene.
Sprite.w
Controls the horizontal visible surface of the image. To have a repeating sprite background you can set the width
or height value bigger than the size of the image.
Sprite.h
Controls the vertical visible surface of the image.
Sprite.xoffset
The horizontal offset within the sprite’s image from where to start painting the sprite’s surface.
Sprite.yoffset
The verical offset within the sprite’s from where to start painting the sprite’s surface.
Sprite.xscale
Horizontal scaling.
Sprite.yscale
Vertical scaling.
Sprite.angle
Rotation of the sprite in radians.
Sprite.color
Background color of the sprite. Use the rgb/hexadecimal CSS notation.
Setters
If you want to change any of those attributes use the following setters:
Sprite.setX(x)
Sprite.setY(y)
Sprite.setW(w)
Sprite.setH(h)
Sprite.setXOffset(x)
Sprite.setYOffset(y)
Sprite.setXScale(xscale)
Sprite.setYScale(yscale)
Sprite.setAngle(radian)
Sprite.setColor(’#333’)
Sprite.setOpacity(0.5)
Sprite.setBackgroundRepeat("repeat-y")
Or one of those helper methods:
Sprite.rotate(radians)
Sprite.scale(xscale[, yscale ])
If y is not defined, y will take the same value as x.
Sprite.move(x, y)
Move the sprite in the direction of the vector (x, y) argument.
Sprite.position(x, y)
Set the position of the sprite (left, top)
Sprite.offset(x, y)
Sprite.size(w, h)
Set the width and height of the visible sprite.
Physics Engine
Collision Detection
These methods are not included in the sprite.js core and needs to be loaded indenpendantly:
<script src="lib/collision.js"></script>
Sprite.isPointIn(x, y)
Returns true if the point (x, y) is within the sprite’s surface.
Sprite.collidesWith(sprite)
Returns true if the sprite is in collision with the passed sprite
Sprite.collidesWithArray(sprites)
Arguments
• sprites (Array) – An array of Sprite objects.
Searches the passed array of sprites for a colliding sprite. If found, that sprite is returned.
Special Effects
There are two methods useful for creating special effects. You can use explode2 to separate the current sprite in two
parts:
Sprite.explode2([position, horizontal=true, layer ])
Arguments
• position (number) – The cut offset / position.
• horizontal (boolean) – Cut horizontaly if true, verticaly if false.
Returns an array of two new sprites that are the two parts of the sprite according to the given position. The
default value for position is half the size of the sprite.
Sprite.explode4([x, y, layer ])
Arguments
• x (number) – The x position where to cute.
• y (number) – The y position where to cute.
• layer (Layer) – the Layer where to create the new Sprites, default being the current
sprite’s Layer.
Return an array of four new sprites that are the split from the center (x, y). The default value for (x, y) is the
center of the sprite.
A List is an iterable object that simplifies the management of an sprite (or any other object) array:
class sjs.List([objects ])
Arguments
• objects (Array) – An array of objects.
Create the object list.
List.add(object | objects)
Add an object or an array of objects to the list.
List.remove(object)
Remove the first matching object from the list.
List.iterate()
Returns an object and increment the pointer. Returns false at the end of the list.
List.list.length
The length of the list.
List.list
Returns the underlying array that the List is managing.
Example of use:
var crate;
while(crate = crates.iterate()) {
crate.applyVelocity();
if(crate.y > 200) {
// remove it from the list
crates.remove(crate);
// remove it from the DOM
crate.remove();
}
}
Keeping track of time in javascript can be difficult. Sprite.js provides a Ticker object to deal with this issue.
A Ticker is an object that keeps track of time properly, so it’s straight forward to render the changes in the scene. The
Ticker gives accurate ticks. A game tick is the time between every Sprites/Physics update in your engine. To setup a
ticker:
function paint(ticker) {
myCycles.next(ticker.lastTicksElapsed);
// do your animation and physics here
}
var ticker = scene.Ticker(paint);
Ticker.run()
Start the ticker.
Ticker.pause()
Pause the ticker.
Ticker.resume()
Resume after a pause.
Ticker.lastTicksElapsed
lastTicksElapsed is the number of ticks elapsed during two runs of the paint function. If performances are good
the value should be 1. If the number is higher than 1, it means that there have been more game ticks than calls
to the paint function since the last time paint was called. In essence, there were dropped frames. The game
loop can use the tick count to make sure that it’s physics end up in the right state, regardless of what has been
rendered.
Ticker.currentTick
The number of elapsed ticks that have been occurred since the creation the the ticker.
A Cycle object manages sprite animations by moving the offsets within the viewport of the sprites.
This is an example cycle with 3 different offset, each lasting 5 game ticks:
cycle.next(5).update();
• ticks (number) – The number of ticks you want to go forward. The default value is 1.
• update (boolean) – If true, the sprite’s offsets will be automaticaly updated.
Calling the next method doesn’t necessarily involve an offset change. It does only when all the ticks on current
triplet have been consumed.
Cycle.go(tick)
Arguments
• tick (number) – Go to the passed tick in the triplets and apply the offsets.
Cycle.reset(update)
Arguments
• update (boolean) – If true, the sprite’s offsets will be automaticaly updated.
Resets the cycle offsets to the original position.
Cycle.update()
Calls the update method on all the sprites.
Cycle.done
This attribute can be checked to determine if the cycle has completed. The value stays false if cycle is repeating.
Cycle.repeat
If set to false, the cycle will stop automaticaly after one run. The default value is true.
The input object remembers user inputs within each game tick:
class scene.Input()
Creates an Input object for the scene.
Input.keyboard
Input.keyboard is a record of which key has been pressed or released. In addition to the normal keyboard keys,
the keyboard object also keep track of these special keyboard states:
keyboard.up
keyboard.right
keyboard.up
keyboard.down
keyboard.enter
keyboard.space
keyboard.ctrl
keyboard.esc
Input.keydown
True if any key is down.
Input.mousedown
True if any mouse button is down.
If you need to know which key has been pressed or released during the last game tick, use these methods:
Input.keyPressed(code)
Arguments
• code (string) – The type of key you want to test. eg: “up”, “left”
Input.keyReleased(code)
Arguments
• code (string) – The type of key you want to test. eg: “up”, “left”
Input.mouse
The mouse object contains the position of the mouse and if the mouse is clicked.
if(mouse.click)
console.log(mouse.click.x, mouse.click.y);
Touch Events
A small swipe updates the keyboard in the wanted direction and a tap will act as the spacebar being pressed. The
mouse position and clicks are also updated by the touch events.
If you need to separate your sprites into logical layers, you can crate a Layer:
Sprite.js provides the Input helper object for managing keyboard input. If you need more complex events handling the
recommanded way is to use event delegation on the Scene object or a specific Layer object:
frontLayer.dom.onclick = function(e) {
var target = e.target || e.srcElement;
target.className = 'selected';
}
scene.dom.onclick = function(e) {
var target = e.target || e.srcElement;
target.className = 'selected';
}
If you need to use events on a Sprite level you can do it if you use the HTML engine:
sprite.dom.addEventListener('click', function(e) {
sprite.dom.className = 'selected';
}, true);
To use some of these feature, you must include an extra javascript files in your web page.
ScrollingSurface object
Scro This object is not included in sprite.js core and needs to be loaded independantly:
<script src="lib/scrolling.js"></script>
This object provide a simple and efficent way to display a moving background within a scene. The object buffers parts
that have already been drawn and only redraw the necessary parts instead of the whole scene at every frame.
function redrawCallback(layer, x, y) {
// draw the necessary sprites on the layer
sprite.canvasUpdate(layer);
}
surface.move(5, 0);
surface.update();
The redrawCallback is called whenever a part of the surface needs to be updated. The absolute position on the surface
is provided for you as an argument to redrawCallback so you may determine what to draw on this layer. The layer
object has a width and height (layer.w, layer.h).
class sjs.ScrollingSurface(scene, w, h, redrawCallback)
Arguments
• scene (Scene) – The scene that will hold the surface.
Math
Path Finding
This object is not included in sprite.js core and needs to be loaded independently:
<script src="lib/path.js"></script>
class Node(...)
Define your own Node object.
Node.neighbors()
Must return a list of Nodes that are the neighbors of the current one.
Node.distance(node)
Returns the distance from this node to another one. It’s mainly used as a hint for the algorithm to find a quicker
way to the end. You may return 0 if you don’t want to implement this method.
Node.equals(node)
Returns true if two nodes are identical, eg:
Node.disabled()
Returns true if the current node cannot be used to find the path.
If you wish to use a entity component model with Sprite.js I would recommend the use of this external library https:
//github.com/batiste/component-entity
3.5 Changelog
21
sprite.js Documentation, Release 1.2.1
C R
Cycle.addSprite() (Cycle method), 15 redrawCallback() (built-in function), 19
Cycle.addSprites() (Cycle method), 15
Cycle.done (Cycle attribute), 16 S
Cycle.go() (Cycle method), 16 Scene.Cycle() (class), 9
Cycle.next() (Cycle method), 15 Scene.Input() (class), 9
Cycle.removeSprite() (Cycle method), 15 scene.Input() (class), 16
Cycle.repeat (Cycle attribute), 16 Scene.Layer() (class), 9, 17
Cycle.reset() (Cycle method), 16 Scene.loadImages() (Scene method), 9
Cycle.update() (Cycle method), 16 Scene.options.autoPause (Scene.options at-
tribute), 9
I Scene.options.h (Scene.options attribute), 9
Input.keyboard (Input attribute), 16 Scene.options.parent (Scene.options attribute), 9
Input.keydown (Input attribute), 16 Scene.options.w (Scene.options attribute), 9
Input.keyPressed() (Input method), 17 Scene.reset() (Scene method), 9
Input.keyReleased() (Input method), 17 Scene.Sprite() (class), 9, 10
Input.mouse (Input attribute), 17 Scene.Ticker() (class), 9, 14
Input.mousedown (Input attribute), 16 Scene.Ticker.options.tickDuration
(Scene.Ticker.options attribute), 14
L Scene.Ticker.options.useAnimationFrame
Layer.options.autoClear (Layer.options at- (Scene.Ticker.options attribute), 14
tribute), 17 ScrollingSurface.move() (ScrollingSurface
Layer.options.parent (Layer.options attribute), method), 19
17 ScrollingSurface.position() (ScrollingSur-
Layer.options.useCanvas (Layer.options at- face method), 19
tribute), 17 ScrollingSurface.update() (ScrollingSurface
List.add() (List method), 13 method), 19
List.iterate() (List method), 14 sjs.Cycle() (class), 15
List.list (List attribute), 14 sjs.List() (class), 13
List.list.length (List.list attribute), 14 sjs.math.hypo() (sjs.math method), 19
List.remove() (List method), 14 sjs.math.mod() (sjs.math method), 19
sjs.normalVector() (sjs method), 19
N sjs.path.find() (sjs.path method), 19
Node() (class), 19 sjs.Scene() (class), 8
Node.disabled() (Node method), 20 sjs.ScrollingSurface() (class), 18
Node.distance() (Node method), 20 Sprite.angle (Sprite attribute), 11
Node.equals() (Node method), 20 Sprite.applyVelocity() (Sprite method), 12
Node.neighbors() (Node method), 20 Sprite.applyXVelocity() (Sprite method), 12
Sprite.applyYVelocity() (Sprite method), 12
23
sprite.js Documentation, Release 1.2.1
T
Ticker.currentTick (Ticker attribute), 15
Ticker.lastTicksElapsed (Ticker attribute), 15
Ticker.pause() (Ticker method), 15
Ticker.resume() (Ticker method), 15
Ticker.run() (Ticker method), 14
24 Index