1.1.6 • Published 5 years ago

myr.js v1.1.6

Weekly downloads
1
License
MIT
Repository
github
Last release
5 years ago

myr.js

myr.js is a WebGL 2 based 2D graphics renderer. The engine is optimized for rendering large amounts of sprites, and it also supports render targets, primitives, shaders and advanced transformations. There are no external dependencies. myr.js has been licensed under the MIT license. All source code is contained in the myr.js file.

Installation

The myr.js file can be included in any ES6 compatible javascript project. No external dependencies are required.

Alternatively, myr.js can be installed as an NPM package using npm install myr.js.

Initialization

myr.js can be initialized by calling the Myr function, which requires a canvas element as an argument. All global functions and objects are members of the returned object. I call this object a myr.js context. The provided canvas must support WebGL 2.

Initialization would typically look like this:

// Create a myr.js context
let myr = new Myr(document.getElementById("some-canvas-id"));

// Access myr.js functions and classes from here on
myr.setClearColor(new Myr.Color(0.2, 0.5, 0.7));

Alternatively, a second parameter can be given to the Myr function, which is a boolean indicating whether anti aliasing should be enabled on this context.

Objects

Two types of myr.js objects exist. There are objects that are exposed through a myr.js context. These objects can only be used for that context. They can be initialized as follows:

// Create a Myriad context
let myr = new Myr(document.getElementById("some-canvas-id"));

// Create a surface to be used in the previously created context
let surface = new myr.Surface(800, 600);

The other type of objects can be accessed directly through the Myr object, and can be shared by multiple contexts. The example below shows using the Color object which is not linked to a specific context:

// Create a Myriad context
let myr = new Myr(document.getElementById("some-canvas-id"));

// Create a color object
let color = new Myr.Color(0.3, 0.5, 0.7);

// Set the created color object as the clear color for the context
myr.setClearColor(color);

The following objects are exposed by a myr.js context.

ObjectDescription
SurfaceA render target which can be rendered to, which may be initialized to an existing image
SpriteA renderable sprite consisting of one or more frames
ShaderA shader

The next objects accessible through the Myr object itself:

ObjectDescription
TransformA 2D transformation
ColorA color containing a red, green, blue and alpha channel
VectorA 2D vector

Namespaces

A myr.js context exposes several namespaces which provide access to specific functions:

NamespaceDescription
primitivesExposes primitive rendering functions
meshExposes mesh rendering functions
utilsExposes utility functions

Global functions

Global functions are members of the object returned by the Myr function. One of the most important tasks of the global functions is maintaining the transform stack. Everything that is rendered is transformed by the Transform on top of this stack. Before applying transformations, it is useful to first save the current transform state using the push() function. The pop() function can be called after the transformations are done to get back to the original state.

FunctionDescription
setClearColor(color)Sets the clear color
setColor(color)Sets the global color filter
setAlpha(alpha)Sets the global transparency
resize(width, height)Resize this renderer
clear()Clears the current target
bind()Binds the default render target
flush()Flush the draw calls
free()Frees myr.js object
getTransform()Get the current transformation
push()Push the transform stack
pop()Pop the transform stack
getWidth()Returns the width of the default render target
getHeight()Returns the height of the default render target
makeSpriteFrame(surface, x, y, width, height, xOrigin, yOrigin, time)Returns a sprite frame
register(name, ...)Register a sprite
isRegistered(name)Check if a sprite is registered
unregister(name)Unregister a sprite
blendEnable()Enable blending
blendDisable()Disable blending
transform(transform)Transform
transformSet(transform)Set transform
translate(x, y)Translate
rotate(angle)Rotate
shear(x, y)Shear
scale(x, y)Scale

setClearColor(color)

Sets the clear color of the myr.js object. When clear() is called, the screen will be cleared using this color.

ParameterTypeDescription
colorColorA color which the canvas will be cleared to when clear() is called

setColor(color)

Sets the global color filter. Every drawn color will be multiplied by this color before rendering.

ParameterTypeDescription
colorColorA color

setAlpha(alpha)

Sets the global alpha (transparency). Every drawn color will be multiplied by this transparency before rendering. Note that this function sets the alpha component of the current clear color set by setColor.

ParameterTypeDescription
alphaNumberA transparency in the range 0, 1

resize(width, height)

Resize the renderer and the canvas used by this Myriad instance.

ParameterTypeDescription
widthNumberThe width in pixels
heightNumberThe height in pixels

clear()

Clears the canvas to the currently set clear color.

bind()

Binds the canvas as the current render target.

flush()

This function finishes all previously given draw calls. This function should be called at the very end of the render loop.

free()

Frees the myr.js object and the OpenGL objects it maintains. Note that this function does not free objects like surfaces, these must be freed individually.

getTransform()

Return the transformation which is currently on top of the stack.

push()

Push the current transformation onto the stack, saving the current transformation state.

pop()

Pop the current transformation from the stack, restoring the last pushed transformation.

getWidth()

Returns the width of the default render target

getHeight()

Returns the height of the default render target

makeSpriteFrame(surface, x, y, width, height, xOrigin, yOrigin, time)

Returns a sprite frame. The result of this function should only be passed to the register function. If the time parameter is less than zero, sprite animation will stop at this frame.

ParameterTypeDescription
surfaceSurfaceA surface containing the frame
xNumberThe x position of the frame on the surface in pixels
yNumberThe y position of the frame on the surface in pixels
widthNumberThe width of the frame in pixels
heightNumberThe height of the frame in pixels
xOriginNumberThe frame x origin in pixels
yOriginNumberThe frame y origin in pixels
timeNumberThe duration of this frame in seconds

register(name, ...)

Registers a new sprite under a name. Once a sprite has been registered, its name can be used to instatiate sprites. When the sprite has been registered previously, the new frames overwrite the old ones.

While the first argument must be the sprite name, the number of following parameters depends on the number of frames. All frames must be passed as arguments after the sprite name. A frame is created using the makeSpriteFrame function.

ParameterTypeDescription
nameStringThe name of the sprite to register

Registering sprites usually happens when loading a sprite sheet. This sheet is first loaded onto a surface, after which all sprites on the sheet are registered to make them available for use. This will usually look like this:

// Load a sprite sheet
sheet = new myr.Surface("source.png");

// Load information about the sprites in this sheet
// This could be loaded from JSon exported by a sprite sheet tool
sprites = loadSprites();

// Register every sprite
for(let i = 0; i < sprites.length; ++i)
    myr.register(
        sprites[i].name,
        myr.makeSpriteFrame(
            sheet,
            sprites[i].x,
            sprites[i].y,
            sprites[i].width,
            sprites[i].height,
            sprites[i].xOrigin,
            sprites[i].yOrigin,
            sprites[i].frameTime));

Note that sprites can be any kind of data, the member names may differ for other formats; it is only necessary that all required information about a sprite is passed. If animated sprites exist, any number of sprite frames can be passed to the register function.

isRegistered(name)

Returns a boolean indicating whether a sprite with the given name has been registered.

ParameterTypeDescription
nameStringThe name of the sprite

unregister(name)

Unregisters a previously registered sprite.

ParameterTypeDescription
nameStringThe name of the sprite to unregister

blendEnable()

Enables blending when drawing. This means that new drawings will not simply overwrite the existing pixels, but blending will be applied depending on the sprite's alpha values. Blending is enabled by default.

blendDisable()

Disables blending when drawing. This means that newly drawn pixels will completely overwrite the pixels previously at that location.

transform(transform)

Transform the current transformation by multiplying it with another transformation.

ParameterTypeDescription
transformTransformA transform to multiply the current transformation with

transformSet(transform)

Set the current transformation by overwriting it. Do not call this function when no custom transformation is on the stack; the root transform may never be modified.

ParameterTypeDescription
transformTransformA transform to set the current transformation to

translate(x, y)

Translate the current transformation.

ParameterTypeDescription
xNumberHorizontal movement
yNumberVertical movement

rotate(angle)

Rotate the current transformation.

ParameterTypeDescription
angleNumberAngle in radians

shear(x, y)

Shear the current transformation.

ParameterTypeDescription
xNumberHorizontal shearing
yNumberVertical shearing

scale(x, y)

Scale the current transformation.

ParameterTypeDescription
xNumberHorizontal scaling
yNumberVertical scaling

Surface

A surface in myr.js can be a render target. After binding it using its member function bind(), all render calls render to this surface. The surface itself can also be rendered. Additionally, the surface may be constructed from images, making surfaces useful for large image or background rendering since large images don't fit well on sprite sheets. Note that surfaces can only render to other targets, never to themselves.

Functions

FunctionDescription
Surface(width, height)Construct from size
Surface(width, height, precision, linear, repeat)Construct from size, precision, interpolation and repeat
Surface(width, height, pixels)Construct from size and pixel data
Surface(width, height, pixels, linear ,repeat)Constructs from size, pixel data, interpolation and repeat
Surface(image)Construct from image
Surface(image, linear, repeat)Construct from image, interpolation and repeat
Surface(image, width, height)Construct from image and size
Surface(image, width, height, linear, repeat)Construct from image, size, interpolation and repeat
bind()Bind the surface
setClearColor(color)Set clear color
clear()Clear the surface
ready()Verify whether the surface is renderable
getWidth()Returns the surface width
getHeight()Returns the surface height
free()Frees all resources used by this surface
draw(x, y)Draws the surface
drawScaled(x, y, xScale, yScale)Draws the surface
drawSheared(x, y, xShear, yShear)Draws the surface
drawRotated(x, y, angle)Draws the surface
drawScaledRotated(x, y, xScale, yScale, angle)Draws the surface
drawTransformed(transform)Draws the surface
drawTransformedAt(x, y, transform)Draws the surface
drawPart(x, y, left, top, width, height)Draws the surface
drawPartTransformed(transform, left, top, width, height)Draws the surface

Surface(width, height)

Constructs a surface of a specific size.

ParameterTypeDescription
widthNumberWidth in pixels
heightNumberHeight in pixels

Surface(width, height, precision, linear, repeat)

Constructs a surface of a specific size with a certain color channel precision. Precision determines the number of bits that are used to describe one color channel. By default, each channel takes 8 bits, so a single pixel will take up 32 bits (RGBA). Increasing this value may be useful when a surface is used to store data instead of an image. The linear interpolation option can be turned on to enable linear interpolation when reading this surface. Interpolation is nearest neighbor by default. The repeat option can be turned on to enable texture repeating when sampling this surface.

ValueBits per channel
08 (default)
116
232
ParameterTypeDescription
widthNumberWidth in pixels
heightNumberHeight in pixels
precisionNumberThe color channel precision
linearBooleanTrue if the surface should be interpolated linearly
repeatBooleanTrue if the surface should repeat when sampling

Surface(width, height, pixels)

Constructs a surface of a specific size from an array of pixels. The pixel array has the size width * height * 4, where every color channel has an entry. The range of the pixel channel values is [0, 255].

ParameterTypeDescription
widthNumberWidth in pixels
heightNumberHeight in pixels
pixelsArrayA Uint8Array with pixels

Surface(width, height, pixels, linear, repeat)

Constructs a surface of a specific size from an array of pixels. The pixel array has the size width * height * 4, where every color channel has an entry. The range of the pixel channel values is [0, 255].

ParameterTypeDescription
widthNumberWidth in pixels
heightNumberHeight in pixels
pixelsArrayA Uint8Array with pixels
linearBooleanTrue if the surface should be interpolated linearly
repeatBooleanTrue if the surface should repeat when sampling

Surface(image)

Constructs a surface from an existing image. The function ready() will return false until the image is loaded.

ParameterTypeDescription
imageString or ImageA URL or Image object referring to a valid image file

Surface(image, linear, repeat)

Constructs a surface from an existing image. The function ready() will return false until the image is loaded.

ParameterTypeDescription
imageString or ImageA URL or Image object referring to a valid image file
linearBooleanTrue if the surface should be interpolated linearly
repeatBooleanTrue if the surface should repeat when sampling

Surface(image, width, height)

Construct a surface from an existing image. The width and height will be set from the beginning instead of after the image has been loaded.

ParameterTypeDescription
imageStringA URL or Image object referring to a valid image file
widthNumberWidth in pixels
heightNumberHeight in pixels

Surface(image, width, height, linear, repeat)

Construct a surface from an existing image. The width and height will be set from the beginning instead of after the image has been loaded.

ParameterTypeDescription
imageStringA URL or Image object referring to a valid image file
widthNumberWidth in pixels
heightNumberHeight in pixels
linearBooleanTrue if the surface should be interpolated linearly
repeatBooleanTrue if the surface should repeat when sampling

bind()

Binds the surface, making it the current render target until another one is bound. After binding, an empty transform is pushed onto the transformation stack.

setClearColor(color)

Set the clear color of this surface. When clear() is called, the surface will be cleared using this color.

ParameterTypeDescription
colorColorA color which the surface will be cleared to when clear() is called

clear()

Clears the surface to the currently set clear color.

ready()

Returns a Boolean indicating whether the surface is ready for use. Surfaces constructed from an image will be ready once the image is loaded. Surfaces that don't require an image are always immediately ready.

getWidth()

Returns the width of the surface in pixels.

getHeight()

Returns the height of the surface in pixels.

free()

Frees the surface and all memory allocated by it.

draw(x, y)

Draws this surface on the currently bound target.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to

drawScaled(x, y, xScale, yScale)

Draws this surface on the currently bound target after applying scaling.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to
xScaleNumberThe horizontal scale factor
yScaleNumberThe vertical scale factor

drawSheared(x, y, xShear, yShear)

Draws this surface on the currently bound target after applying shearing.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to
xShearNumberHorizontal shearing
yShearNumberVertical shearing

drawRotated(x, y, angle)

Draws this surface on the currently bound target after applying rotation.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to
angleNumberThe rotation in radians

drawScaledRotated(x, y, xScale, yScale, angle)

Draws this surface on the currently bound target after applying both scaling and rotation.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to
xScaleNumberThe horizontal scale factor
yScaleNumberThe vertical scale factor
angleNumberThe rotation in radians

drawTransformed(transform)

Draws this surface on the currently bound target after applying a transformation to it.

ParameterTypeDescription
transformTransformA transformation to apply to this surface

drawTransformedAt(x, y, transform)

Draws this surface on the currently bound target at a certain position after applying a transformation to it.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to
transformTransformA transformation to apply to this surface

drawPart(x, y, left, top, width, height)

Draws a part of this surface on the currently bound render target. Make sure the specified region is part of the surface; rendering parts that fall outside this surface results in undefined behavior.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to
leftNumberThe X position on the surface to draw from
topNumberThe Y position on the surface to draw from
widthNumberThe width of the region to draw
heightNumberThe height of the region to draw

drawPartTransformed(transform, left, top, width, height)

Draws a part of this surface on the currently bound render target.

ParameterTypeDescription
transformTransformA transformation to apply to this surface
leftNumberThe X position on the surface to draw from
topNumberThe Y position on the surface to draw from
widthNumberThe width of the region to draw
heightNumberThe height of the region to draw

Sprite

A sprite in myr.js is a renderable image consisting of one or more frames. Sprite sources must be registered using register before they can be instantiated. Sprites are constructed by referencing these sources.

Typically, one big surface should contain all sprites (it will be a sprite atlas). In this way, sprite rendering is much more efficient than surface rendering.

Functions

FunctionDescription
Sprite(name)Constructs a sprite
animate(timeStep)Animates the sprite
setFrame(frame)Set the current frame
getFrame()Returns the current frame
isFinished()Returns whether the animation is finished
getFrameCount()Returns the number of frames
getWidth()Returns the sprite width
getHeight()Returns the sprite height
getOriginX()Returns the X origin
getOriginY()Returns the Y origin
getUvLeft()Returns the left UV coordinate.
getUvTop()Returns the top UV coordinate.
getUvWidth()Returns the width of the sprite in UV space.
getUvHeight()Returns the height of the sprite in UV space
draw(x, y)Draws the sprite
drawScaled(x, y, xScale, yScale)Draws the sprite
drawSheared(x, y, xShear, yShear)Draws the sprite
drawRotated(x, y, angle)Draws the sprite
drawScaledRotated(x, y, xScale, yScale, angle)Draws the sprite
drawTransformed(transform)Draws the sprite
drawTransformedAt(x, y, transform)Draws the sprite
drawPart(x, y, left, top, width, height)Draws the sprite
drawPartTransformed(transform, left, top, width, height)Draws the sprite

Sprite(name)

Constructs a sprite from a registered source.

ParameterTypeDescription
nameStringThe sprite source

animate(timeStep)

Advances the animation frame of this sprite according to its frame times. When the maximum frame has been reached, the animation rewinds. If a sprite only has one frame, this method does nothing. Note that the animation stops at any frame with a time value below zero.

ParameterTypeDescription
timeStepNumberThe current time step, which is the time the current animation frame takes

setFrame(frame)

Sets the current frame index of this sprite.

ParameterTypeDescription
frameNumberThe frame index this sprite should be at, starting at zero

getFrame()

Returns the current frame index.

isFinished()

Returns a boolean indicating whether the animation is finished. A sprite animation is finished when any frame with a time value below zero is reached. If the frame is set to another frame using setFrame after this, the animation will continue again.

getFrameCount()

Returns the total number of frames for this sprite.

getWidth()

Returns the width of the sprite in pixels.

getHeight()

Returns the height of the sprite in pixels.

getOriginX()

Returns the X origin of this sprite's current frame.

getOriginY()

Returns the Y origin of this sprite's current frame.

getUvLeft()

Returns the left UV coordinate.

getUvRight()

Returns the top UV coordinate.

getUvWidth()

Returns the width of the sprite in UV space.

getUvHeight()

Returns the height of the sprite in UV space

draw(x, y)

Draws this sprite on the currently bound target.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to

drawScaled(x, y, xScale, yScale)

Draws this sprite on the currently bound target after applying scaling.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to
xScaleNumberThe horizontal scale factor
yScaleNumberThe vertical scale factor

drawSheared(x, y, xShear, yShear)

Draws this sprite on the currently bound target after applying shearing.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to
xShearNumberHorizontal shearing
yShearNumberVertical shearing

drawRotated(x, y, angle)

Draws this sprite on the currently bound target after applying rotation.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to
angleNumberThe rotation in radians

drawScaledRotated(x, y, xScale, yScale, angle)

Draws this sprite on the currently bound target after applying both scaling and rotation.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to
xScaleNumberThe horizontal scale factor
yScaleNumberThe vertical scale factor
angleNumberThe rotation in radians

drawTransformed(transform)

Draws this sprite on the currently bound target after applying a transformation to it.

ParameterTypeDescription
transformTransformA transformation to apply to this sprite

drawTransformedAt(x, y, transform)

Draws this sprite on the currently bound target at a certain position after applying a transformation to it.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to
transformTransformA transformation to apply to this sprite

drawPart(x, y, left, top, width, height)

Draws a part of this sprite on the currently bound render target. Make sure the specified region is part of the sprite; rendering parts that fall outside this sprite results in undefined behavior.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to
leftNumberThe X position on the sprite to draw from
topNumberThe Y position on the sprite to draw from
widthNumberThe width of the region to draw
heightNumberThe height of the region to draw

drawPartTransformed(transform, left, top, width, height)

Draws a part of this sprite on the currently bound render target.

ParameterTypeDescription
transformTransformA transformation to apply to this surface
leftNumberThe X position on the sprite to draw from
topNumberThe Y position on the sprite to draw from
widthNumberThe width of the region to draw
heightNumberThe height of the region to draw

Shader

A shader in myr.js is a renderable image that is rendered using a custom pixel shader written by the user. Shaders can be provided with one or more surfaces to read from, and one or more variables can be provided to the shader. Pixel shaders must be written in WebGL 2 compliant GLSL.

The size of the rendered result is equal to the size of the first surface provided to it, or alternatively (or when no surfaces are provided) to a size set by the user.

Functions

FunctionDescription
Shader(shader, surfaces, variables)Constructs a shader
getWidth()Returns the shader width
getHeight()Returns the shader height
setVariable(name, value)Set one of the variables' values
setSurface(name, surface)Set one of the input surfaces' surface
setSize(width, height)Set the size of this shader
free()Free this shader
draw(x, y)Draws the shader
drawScaled(x, y, xScale, yScale)Draws the shader
drawSheared(x, y, xShear, yShear)Draws the shader
drawRotated(x, y, angle)Draws the shader
drawScaledRotated(x, y, xScale, yScale, angle)Draws the shader
drawTransformed(transform)Draws the shader
drawTransformedAt(x, y, transform)Draws the shader
drawPart(x, y, left, top, width, height)Draws the shader
drawPartTransformed(transform, left, top, width, height)Draws the shader

Shader(shader, surfaces, variables)

Constructs a shader using WebGL 2 compliant GLSL code, and optionally, surface and variable inputs. The surfaces and variables arrays are arrays of strings. Inside the shader code, their values are accessible by these strings as names. To assign surfaces and values to these, the functions setSurface() and setVariable() are used.

ParameterTypeDescription
shaderStringThe GLSL code to execute when this shader runs
surfacesArrayAn array of names for surface inputs
variablesArrayAn array of variables to create in this shader

The GLSL code to provide is not the entire shader. A simple complete GLSL pixel shader that renders red pixels could look like this:

layout(location = 0) out lowp vec4 color;

void main() {
    color = vec4(1, 0, 0, 1);
}

The GLSL code that should be provided to the custom shader is the main function of the shader, preceeded by any custom functions. However, uniforms and uniform blocks are already predefined, they should not be included.

void main() {
    color = vec4(1, 0, 0, 1);
}

Inside the GLSL code, several variables are accessible for the user besides the surfaces and variables. These are:

  • uv, a mediump vec2 representing the UV coordinates of the current pixel inside the drawing area of this shader.
  • pixel, a mediump vec2 representing the pixel of the source currently being shaded. This variable ranges from [0, 0] in the left top of the image to [width, height], where width and height are the source's width and height in pixels.
  • pixelSize, a mediump vec2 containing the UV size of one pixel. Sampling a pixel to the right for example can be done using texture(source, vec2(uv.x + pixelSize.x, uv.y)).
  • colorFilter, a lowp vec4 containing the current color filter (set by setColor).
  • color, a lowp vec4 where the output pixel color should be written to.

Before drawing a shader, ensure that all variables and surfaces have been set using the setSurface() and setVariable() functions. Not doing this may and probably will result in undefined behavior.

getWidth()

Returns the width of the shader in pixels. If setSurface() was called on the first surface in this shader's surfaces array, the width will be equal to that surface's width. Otherwise, the width will be equal to the width given to this shader by the setSize() function.

getHeight()

Returns the height of the shader in pixels. If setSurface() was called on the first surface in this shader's surfaces array, the height will be equal to that surface's height. Otherwise, the height will be equal to the height given to this shader by the setSize() function.

setVariable(name, value)

Set the value of one of this shader's variables. The variable name should have been declared by passing it to the variables array when the shader was created. The value must be a number, and will be accessible inside the GLSL code under its name with the mediump float type.

ParameterTypeDescription
nameStringThe variable name
valueNumberThe value

setSurface(name, surface)

Set the surface of one of this shader's surfaces. The surface name should have been declared by passing it to the surfaces array when the shader was created. The value must be a Surface, and will be accessible inside the GLSL code under its name with the sampler2D type.

ParameterTypeDescription
nameStringThe surface name
surfaceSurfaceThe surface

setSize(width, height)

Sets the size of this shader. This should not be used when the the surfaces list was not empty when constructing this shader; in that case, the shader size will be equal to the size of its first surface. If no surfaces are provided, the shader size should be set using this function.

free()

Free all resources occupied by this shader. When the shader is no longer used, this function should be called to ensure the occupied memory is freed.

draw(x, y)

Draws this shader on the currently bound target.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to

drawScaled(x, y, xScale, yScale)

Draws this shader on the currently bound target after applying scaling.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to
xScaleNumberThe horizontal scale factor
yScaleNumberThe vertical scale factor

drawSheared(x, y, xShear, yShear)

Draws this shader on the currently bound target after applying shearing.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to
xShearNumberHorizontal shearing
yShearNumberVertical shearing

drawRotated(x, y, angle)

Draws this shader on the currently bound target after applying rotation.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to
angleNumberThe rotation in radians

drawScaledRotated(x, y, xScale, yScale, angle)

Draws this shader on the currently bound target after applying both scaling and rotation.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to
xScaleNumberThe horizontal scale factor
yScaleNumberThe vertical scale factor
angleNumberThe rotation in radians

drawTransformed(transform)

Draws this shader on the currently bound target after applying a transformation to it.

ParameterTypeDescription
transformTransformA transformation to apply to this shader

drawTransformedAt(x, y, transform)

Draws this shader on the currently bound target at a certain position after applying a transformation to it.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to
transformTransformA transformation to apply to this shader

drawPart(x, y, left, top, width, height)

Draws a part of this shader on the currently bound render target. Make sure the specified region is part of the shader; rendering parts that fall outside this shader results in undefined behavior.

ParameterTypeDescription
xNumberThe X position to draw to
yNumberThe Y position to draw to
leftNumberThe X position on the shader to draw from
topNumberThe Y position on the shader to draw from
widthNumberThe width of the region to draw
heightNumberThe height of the region to draw

drawPartTransformed(transform, left, top, width, height)

Draws a part of this shader on the currently bound render target.

ParameterTypeDescription
transformTransformA transformation to apply to this shader
leftNumberThe X position on the shader to draw from
topNumberThe Y position on the shader to draw from
widthNumberThe width of the region to draw
heightNumberThe height of the region to draw

Transform

The transform object wraps a homogeneous 2D transformation matrix. Several different transform functions are provided, but the matrix can also be filled by hand. Transform objects are used in the global transformation stack to transform everything that is being rendered.

Functions

FunctionDescription
Transform()Constructs as identity transform
Transform(_00, _10, _20, _01, _11, _21)Constructs from matrix values
apply(vector)Apply to a vector
copy()Returns a copy
identity()Set to identity
set(transform)Make equal to another transform
multiply(transform)Multiply with another transform
rotate(angle)Rotate
shear(x, y)Shear
translate(x, y)Translate
scale(x, y)Scale
invert()Invert

Transform()

Constructs a Transform object, which is initialized as the identity matrix (no transform).

Transform(_00, _10, _20, _01, _11, _21)

Constructs a Transform object with custom values. Note that only the top two rows of the matrix can be entered, since the bottom row for 2D transformations will always be [0, 0, 1].

ParameterTypeDescription
_00NumberValue 0, 0 of the matrix
_10NumberValue 1, 0 of the matrix
_20NumberValue 2, 0 of the matrix
_01NumberValue 0, 1 of the matrix
_11NumberValue 1, 1 of the matrix
_21NumberValue 2, 1 of the matrix

apply(vector)

Multiplies the given vector by this transformation matrix. This function may prove useful when a coordinate instead of a rendering call must be transformed.

ParameterTypeDescription
vectorVectorA vector object to transform

copy()

Returns a copy of this transform object.

identity()

Sets the transformation to the identity matrix.

set(transform)

Sets the transformation to another transformation.

ParameterTypeDescription
transformTransformA transform object

multiply(transform)

Multiplies this transformation with another transformation by matrix multiplication. This is useful for combining different transforms together.

ParameterTypeDescription
transformTransformA transform object

rotate(angle)

Rotate by a number of radians.

ParameterTypeDescription
angleNumberThe number of radians to rotate by

shear(x, y)

Shear this transformation.

ParameterTypeDescription
xNumberHorizontal shear
yNumberVertical shear

translate(x, y)

Translate this transformation.

ParameterTypeDescription
xNumberHorizontal translation
yNumberVertical translation

scale(x, y)

Scale this transformation.

ParameterTypeDescription
xNumberHorizontal scale
yNumberVertical scale

invert()

Invert this transformation.

Color

This object represents a color with a red, green, blue and alpha component.

Functions

FunctionDescription
Color(r, g, b)Construct from RGB
Color(r, g, b, a)Construct from RGBA
toHSV()Convert to HSV values
toHex()Convert to hexadecimal string
copy()Copy this color
add(color)Adds another color to itself
multiply(color)Multiplies with another color

Global functions

FunctionDescription
fromHSV(h, s, v)Constructs a color from hue, saturation and value
fromHex(hex)Constructs a color from a hexadecimal string

Constants

ConstantDescription
BLACKBlack
BLUEBlue
GREENGreen
CYANCyan
REDRed
MAGENTAMagenta
YELLOWYellow
WHITEWhite

Color(r, g, b)

Constructs a color object from red, green and blue. The values must lie in the range 0, 1. The color will have an alpha value of 1.0.

ParameterTypeDescription
rNumberRed value in the range 0, 1
gNumberGreen value in the range 0, 1
bNumberBlue value in the range 0, 1

Color(r, g, b, a)

Constructs a color object from red, green, blue and alpha. The values must lie in the range 0, 1.

ParameterTypeDescription
rNumberRed value in the range 0, 1
gNumberGreen value in the range 0, 1
bNumberBlue value in the range 0, 1
aNumberAlpha value in the range 0, 1

toHSV()

Returns an object with the members h, s and v, representing this color's hue, saturation and value.

toHex()

Returns a hexadecimal string representing this color. Note that hexadecimal color representations don't include an alpha channel, so this information is lost after converting the color.

copy()

Returns a copy of this color.

add(color)

Adds another color to itself.

ParameterTypeDescription
colorColorA color object

multiply(color)

Multiplies this color with another color.

ParameterTypeDescription
colorColorA color object

fromHSV(h, s, v)

Constructs a color from hue, saturation and value.

ParameterTypeDescription
hNumberHue value in the range 0, 1
sNumberSaturation value in the range 0, 1
vNumberValue value in the range 0, 1

fromHex(hex)

Constructs a color from a hexadecimal string. The string must not contain a prefix like 0x or #. If the string has six characters, the red, green and blue components will be read from it. If the string has eight characters, the alpha channel will also be read.

Vector

This object represents a vector in 2D space. Several useful vector operation functions are provided.

Functions

FunctionDescription
Vector(x, y)Construct from x and y
copy()Returns a copy
add(vector)Add
subtract(vector)Subtract
negate()Negate
dot(vector)Dot product
length()Length
multiply(scalar)Multiply
divide(scalar)Divide
normalize()Normalize
rotate(angle)Rotate
angle()Returns the angle
reflect(vector)Reflect
equals(vector)Checks for equality

Vector(x, y)

Constructs a vector object.

ParameterTypeDescription
xNumberX value
yNumberY value

copy()

Returns a copy of this vector object.

add(vector)

Add another vector to this one.

ParameterTypeDescription
vectorVectorA vector object

subtract(vector)

Subtract another vector from this one.

ParameterTypeDescription
vectorVectorA vector object

negate()

Negate the vector values.

dot(vector)

Returns the dot product of this vector and another one.

ParameterTypeDescription
vectorVectorA vector object

length()

Returns the length of the vector.

multiply(scalar)

Multiplies the vector by a scalar.

ParameterTypeDescription
scalarNumberA number

divide(scalar)

Divides the vector by a scalar.

ParameterTypeDescription
scalarNumberA number

normalize()

Normalizes the vector.

rotate(angle)

Rotates this vector by a given angle.

ParameterTypeDescription
angleNumberAn angle in radians.

angle()

Returns the angle this vector is pointing towards.

reflect(vector)

Reflects the vector against the given normal vector.

equals(vector)

Returns a boolean indicating whether the vector is equal to another vector.

ParameterTypeDescription
vectorVectorA vector object

Primitives

The primitives namespace exposes several functions which can be used for primitive rendering.

Functions

FunctionDescription
drawPoint(color, x, y)Draws a colored point
drawLine(color, x1, y1, x2, y2)Draws a line segment
drawLineGradient(color1, x1, y1, color2, x2, y2)Draws a gradient line segment
drawRectangle(color, x, y, width, height)Draws a rectangle
drawCircle(color, x, y, radius)Draws a circle
drawTriangle(color, x1, y1, x2, y2, x3, y3)Draws a colored triangle
drawTriangleGradient(color1, x1, y1, color2, x2, y2, color3, x3, y3)Draws a gradient triangle
fillRectangle(color, x, y, width, height)Draws a colored rectangle
fillRectangleGradient(color1, color2, color3, color4, x, y, width, height)Draws a gradient rectangle
fillCircle(color, x, y, radius)Draws a colored circle
fillCircleGradient(colorStart, colorEnd, x, y, radius)Draws a gradient circle

drawPoint(color, x, y)

Draws a colored pixel at the specified coordinates.

ParameterTypeDescription
colorColorThe point color
xNumberThe x coordinate
yNumberThe y coordinate

drawLine(color, x1, y1, x2, y2)

Draws a single line segment with a color.

ParameterTypeDescription
colorColorThe line color
x1NumberThe start point x coordinate
y1NumberThe start point y coordinate
x2NumberThe end point x coordinate
y2NumberThe end point y coordinate

drawLineGradient(color1, x1, y1, color2, x2, y2)

Draws a single line segment with a color gradient.

ParameterTypeDescription
color1ColorThe line color at the start point
x1NumberThe start point x coordinate
y1NumberThe start point y coordinate
color2ColorThe line color at the end point
x2NumberThe end point x coordinate
y2NumberThe end point y coordinate

drawRectangle(color, x, y, width, height)

Draws a rectangle.

ParameterTypeDescription
colorColorThe line color
xNumberThe left top x coordinate
yNumberThe left top y coordinate
widthNumberThe rectangle width
heightNumberThe rectangle height

drawCircle(color, x, y, radius)

Draws a circle with a radius around an origin.

ParameterTypeDescription
colorColorThe line color
xNumberThe center's x coordinate
yNumberThe center's y coordinate
radiusNumberThe circle radius

drawTriangle(color, x1, y1, x2, y2, x3, y3)

Draws a colored triangle.

ParameterTypeDescription
colorColorThe fill color
x1NumberThe first point's x coordinate
y1NumberThe first point's y coordinate
x2NumberThe second point's x coordinate
y2NumberThe second point's y coordinate
x3NumberThe third point's x coordinate
y3NumberThe third point's y coordinate

drawTriangleGradient(color1, x1, y1, color2, x2, y2, color3, x3, y3)

Draws a triangle with a gradient fill. Each point has a color, and the colors are interpolated along the triangle.

ParameterTypeDescription
color1ColorThe first point's color
x1NumberThe first point's x coordinate
y1NumberThe first point's y coordinate
color2ColorThe second point's color
x2NumberThe second point's x coordinate
y2NumberThe second point's y coordinate
color3ColorThe third point's color
x3NumberThe third point's x coordinate
y3NumberThe third point's y coordinate

fillRectangle(color, x, y, width, height)

Draws a colored rectangle.

ParameterTypeDescription
colorColorThe fill color
xNumberThe left top x coordinate
yNumberThe left top y coordinate
widthNumberThe rectangle width
heightNumberThe rectangle height

fillRectangleGradient(color1, color2, color3, color4, x, y, width, height)

Draws a rectangle with a gradient fill. Each point has a color, and the colors are interpolated along the rectangle.

ParameterTypeDescription
color1ColorThe left top color
color2ColorThe right top color
color3ColorThe left bottom color
color4ColorThe right bottom color
xNumberThe left top x coordinate
yNumberThe left top y coordinate
widthNumberThe rectangle width
heightNumberThe rectangle height

fillCircle(color, x, y, radius)

Draws a colored circle with a radius around an origin.

ParameterTypeDescription
colorColorThe fill color
xNumberThe center's x coordinate
yNumberThe center's y coordinate
radiusNumberThe circle radius

fillCircleGradient(colorStart, colorEnd, x, y, radius)

Draws a gradient circle with a radius around an origin.

ParameterTypeDescription
colorStartColorThe color at the center
colorEndColorThe color at the edge
xNumberThe center's x coordinate
yNumberThe center's y coordinate
radiusNumberThe circle radius

Mesh

The mesh namespace exposes several functions which can be used for mesh rendering. Meshes consist of textured triangles; both surfaces and sprites can be used as a source texture.

Functions

FunctionDescription
drawTriangle(source, x1, y1, u1, v1, x2, y2, u2, v2, x3, y3, u3, v3)Draws a textured triangle

drawTriangle(source, x1, y1, u1, v1, x2, y2, u2, v2, x3, y3, u3, v3)

Draws a textured triangle. The source can be either a surface or a sprite. If a sprite is used as the source, the current frame of the sprite is used. Note that texture coordinates range from 0 to 1.

ParameterTypeDescription
sourceSurface or SpriteThe image to draw a part of
x1NumberThe first point's x coordinate
y1NumberThe first point's y coordinate
u1NumberThe first point's texture x coordinate
v1NumberThe first point's texture y coordinate
x2NumberThe second point's x coordinate
y2NumberThe second point's y coordinate
u2NumberThe second point's texture x coordinate
v2NumberThe second point's texture y coordinate
x3NumberThe third point's x coordinate
y3NumberThe third point's y coordinate
u3NumberThe third point's texture x coordinate
v3NumberThe third point's texture y coordinate

Utils

Functions

FunctionDescription
loop(update)Calls the function update on every vertical sync

loop(update)

After calling this function, the provided update function is called for every vertical synchronization. This usually means the function is called sixty frames per second. The argument timeStep is passed to the function, which is the portion of a second the current frame takes; this will be 1/60 when the browser updates at 60 frames per second. When rendering at this frequency, screen tearing is usually prevented.

The update function should return a boolean. As long as true is returned, the function keeps being called; when false is returned, the loop stops.

ParameterTypeDescription
updateFunctionA function that is called for every update
1.1.6

5 years ago

1.1.5

5 years ago

1.1.4

5 years ago

1.1.3

5 years ago

1.1.2

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago

0.5.0

6 years ago

0.4.0

6 years ago

0.3.3

6 years ago

0.3.2

6 years ago

0.3.1

6 years ago

0.3.0

6 years ago