SortaCanvas User Guide, revision 2.1
h
tussiez (747)

This is a draft of my JavaScript library, SortaCanvas. This is a JS canvas library that is similar to p5.js, but with less of the drawbacks.

User guide file: https://sortacanvas.sortagames.repl.co/userguide.md

Main page:
https://sortacanvas.sortagames.repl.co/

SortaCanvas User Guide

NOTE: This is a working draft!

Adding the library

Haha yes, the library is a module. If you haven't already, make your script a module by adding the argument type="module" to your <script> tag.
To import, use

import SortaCanvas from 'https://SortaCanvas.sortagames.repl.co/lib.js'

Setup

To make your <canvas> element availabe to the library, you'll need to run SortaCanvas.init(). There are three arguments you need to add here, from left to right:
1. The <canvas> element.
2. Whether or not you want to use a custom render loop (true/false). If you set this to false, SortaCanvas will start rendering immediately. You can toggle this later with SortaCanvas.doRender(boolean)
3. The TWEEN.js variable, if you wish to use Move() to animate objects. This argument is optional.

Setup in Web Workers

As of now, this functionality is untested, but in theory using SortaCanvas as a Web Worker is possible.
To pass the canvas element, you'll need to run

canvas.transferControlToOffscreen();

and pass the canvas variable through a postMessage into your Web Worker.

Resizing Canvas

You can resize the canvas with:

SortaCanvas.setSize(width,height);//In pixels

"Fullscreen" Mode

You can enable "fullscreen" mode (fit to tab size) with:

SortaCanvas.enableFullscreen();

Setting Background Color

You can set the background color (and opacity) of the canvas. By changing opacity, you can make trails appear.
This function accepts a CSS color:

SortaCanvas.setBackground('cssColor');

Example:

SortaCanvas.setBackground('rgba(0,0,0,.75)');

Strict Mode

Strict Mode is disabled by default. Enabling this with SortaCanvas.enableStrictMode() (and disabling with SortaCanvas.disableStrictMode()) will disable all fallbacks and instead throw errors every time. For example, if strictMode is disabled and you set the color of a rectangle to a number, the object's color will default to black. However, if strictMode is enabled, this will throw an error.

Rendering

To render objects in your own animation loop, use SortaCanvas.render(). This also updates the animation library, if set up.

If you tell SortaCanvas to render independently, you have the option to toggle this with

SortaCanvas.toggleRender(true/false)

Drawing Objects

Objects in SortaCanvas are constructors. This means you can "create" copies of these with var z = new foo.bar(x,y) and save them as variables. This makes updating position, size, and other arguments easy.

Arguments

Most of these arguments are self explanatory, but you can use this as a cheatsheet:

x = left position of the object, in pixels
y = top position of the object, in pixels
height = height of the object, in pixels
width = width of the object, in pixels
color = the color of the object, CSS colors are supported
name = optional variable, can be used in SortaCanvas.getObjectByName(name)
radius = the radius of the circle
src = the URL of the image you wish to load
font = the font size and font name of the text you wish to display (e.g 16px Arial)
outline = boolean, show text outline or not

Rectangle

To create a rectangle, use the following code:

let rect = new SortaCanvas.Rectangle(x,y,height,width,color,name)

Circle

Use the code below to make a circle:

let circle = new SortaCanvas.Circle(x,y,radius,color,name)

Image

To create an image object, use the following code:

let image = new SortaCanvas.Image(x,y,height,width,name)

Text

To draw text on the canvas:

let text = new SortaCanvas.Text(x,y,text,font,color,text,name)

Additional Arguments

To reduce the complexity of objects, there are a few extra arguments available outside of the inital function (new X(y,z,a,b,c))

Disabling Object Picking

You may wish to disable object picking on some objects, such as backgrounds and static objects.

To disable object picking, simply do

object.pick = false;

If you need to enable picking again later, change this to true.

Object Rotation

EXPERMIENTAL
You can rotate shapes with

object.rotation = degrees;

Note: Object picking/collisions do not behave correctly with this enabled. These objects are treated as they are not rotated.
Note: For obvious reasons, you cannot rotate circles.

Object Collision Detection

EXPERIMENTAL
The render loop checks for object collisions by default.
To tell if an object is colliding with another, use

object.collide = boolean;//Read-only variable

If an object is touching/inside another, this property is set to true. If not, this property is false.

Object Methods

By default, an object isn't added to the canvas yet.
To add the object, use

SortaCanvas.add(object)

To remove the object, use

SortaCanvas.remove(object)

If you defined an object by name earlier, you can get the object with:

let obj = SortaCanvas.getObjectByName('name')

Updating an object

Almost all object arguments can be dynamically updated at runtime.
To do this, simply update the variable by its name. Error checking is also done on every draw call, so errors will be thrown if invalid data is used (e.g color is a number)

No errors will be thrown if unused variables are defined.

Example

let text = new SortaCanvas.Text(100,50,'Play SortaCraft!','16px Arial','brown');
SortaCanvas.add(text);

//Even after adding the text object to the scene, you can update it:
text.x = 90;
text.y = 75;
text.font = '20px Verdana';
//All changes will be reflected on the next draw call.

Animation (Beta)

This library supports using TWEENjs for animating property changes of objects.

As of now, the only function available is

Move (Animation)

SortaCanvas.Move allows for a smooth transition for an object to move between two positions.
There are only a few arguments:
object, the object you wish to animate
x, the X position you want to move the object to
y, the Y position you want to move the object to
time, the time (in seconds) you wish the animation to last for. This determines the animation speed.

Usage:

SortaCanvas.Move(object,x,y,time);

Example:

SortaCanvas.Move(rect,175,25,1);

Rotate (Animation)

SortaCanvas.Rotation animates an object rotation.
To use this, you'll need three arguments:
object, the object you want to rotate
rotation, the amount in degrees you want to set the object's rotation to
time, the time (in seconds) the duration of the animation should be.

Usage:

SortaCanvas.Rotate(object,rotation,time)

Example:

SortaCanvas.Rotate(rect,45,1)

(Coming soon): Scale

Object Picking

In this case, Object Picking is when you take a set of coordinates (e.g mouse position), and check if any objects on the canvas are present there.
To do this in SortaCanvas, run SortaCanvas.raycast(x,y).
If an object is found at the input position, this function returns the object. Otherwise, raycast returns undefined.
This function is used in SortaCanvas' built-in user events.

User Events

SortaCanvas has custom events that fire on user input. These behave similarly to the DOM events mousedown, mouseup, mousemove, touchstart, touchmove, contextmenu, and touchend.
When an object is detected at the mouse coordinates, along with passing the event, the coordinates of the mouse relative to the canvas is sent with the object picked.

Some use cases include: the SortaCraft inventory, animations, games, drag and drop functionality, and much more.

Setting up canvas events

To add the event listeners, use SortaCanvas.addEventListeners(). This function will not work if SortaCanvas is imported in a Web Worker.

Adding event listeners

To listen for these custom events, use

SortaCanvas.addEventListener('event-name',handlerFunction)

where 'event-name' is the name of the event, which can be one of the following:

  • mousedown (mouse is pressed down without object)
  • mousedownhit (mouse pressed down with object)
  • mousemove (mouse is moved without object)
  • mousemovehit (mouse is moved with object)
  • mouseup (mouse is lifted without object)
  • mouseuphit (mouse is lifted with object)
  • contextmenu (right clicked without object)
  • contextmenuhit (right clicked with object)
    The same events above are also called on touchstart, touchend, and touchmove, and are supported by default.

Additionally, collision is fired when an object collides.

When an event is fired with hit, the object sent is:

{
object, //the object picked
event, //the DOM event
pos, //the mouse coordinates local to the canvas element
}

When an event is fired without hit, the object variable is not passed.

The collision event only passes object when fired.

Web Workers: manually setting up event listeners

If you wish to use SortaCanvas in a Web Worker and need to use the built-in event listeners, you'll need to pass these events to your worker and then pass them to SortaCanvas.

On the events mousedown, mouseup, mousemove, touchstart, touchmove, contextmenu and touchend, pass the default event object to the corresponding functions in SortaCanvas:

SortaCanvas.mouseDownEvent(e);//works with touchstart
SortaCanvas.mouseUpEvent(e);//works with touchend
SortaCanvas.mouseMoveEvent(e);//works with touchmove
SortaCanvas.contextMenuEvent(e);

Internal Functions

The functions described below are used internally in SortaCanvas.
You can use these, if you wish.

calculateMousePos(x,y) calculates mouse coordinates relative to the canvas
raycast(x,y) - object picking
log(text) - custom logging, caps at 1000 messages
warn(text) - custom logging, caps @ 1000 warnings
error(text) - custom logging, caps @ 1000 errors
throwError(text) - throws actual errors, caps @ 1000
dispatch(event,data) - "fires" events to event listeners
calculateSize({x,y,height,width}) - calculates size for circles and text, returns object: {x,y,height,width}
getBounds({x,y,height,width}) - Calculates object boundaries, used with calculateSize({}). Returns object: {min:{x,y},max:{x,y}}
collision(obj,obj2) - Determines if two objects are touching/inside eachother

Extras

randomColor() generates a random RGB color

You are viewing a single comment. View All