Reference

Reference ❯ jsCanvas Reference

Overview

How jsCanvas Draws top ↑

When you begin a new project in jsCanvas you'll notice that it consists of a tab called Main and some template code. Your project can consist of several tabs, the initial one is always called Main. If you add more tabs they will be listed across the top.

function setup() {
    print("hello world");
}

function draw() {
    background(40,40,50);
    fill(150,200,30);
    stroke(200,30,150);
    strokeWidth(10);
    rect(20,20,100,100);
}

This is the framework that your project will use to run. There are two functions defined for you initially: setup() and draw().

setup() and draw() are executed by jsCanvas when you press the execute button to run your project. The setup() function is called once, at the start, and then the draw() function is called repeatedly. In setup() jsCanvas expects you to set up your initial program state, and in draw() you can tell jsCanvas to render graphics onto the screen, update your program state over time, and so on.

There are two other important functions that deal with one method for how the user can interact with a running jsCanvas program (the other method is to use parameters). These are the touched and key functions. The first deals with any touch or mouse events, the second with any keyboard events (note that on mobile devices, it may not be possible to use the keyboard). These functions are called between repeats of the draw function.

In the next two sections we will cover these functions in detail.

The draw() function top ↑

When you press the execute button, the draw() function is repeatedly executed by jsCanvas.

function draw() {
    // Set the background colour to blueish
    background(100,120,180);

    // Set the fill colour to red
    fill(255,0,0);

    // Set a wide outline
    strokeWidth(5);

    // Set the outline colour to white
    stroke(255);

    // Draw a red circle with a white outline
    // In the center of the screen
    ellipse( WIDTH/2, HEIGHT/2, 200 );
}

Note that the above code will run many times every second. That is, you are telling jsCanvas to paint the background blue and draw a red circle with a white outline several times per second, from scratch. It does this so that you can create smooth motion by changing your program state over time, and updating your drawing code to reflect the new state. For example, you might make the circle bounce on the ground by changing its Y-position (the second parameter to ellipse()) every frame.

The setup() function top ↑

When you press the execute button jsCanvas will call the setup() function once, before it begins calling the draw() function. In here you can perform any once-off computations, set up program state, set the display mode, and do things that you don't need to do every frame. For example, the setup() function below creates a global variable controlled by a slider. This variable is then used in the draw() function to control the Y-position of a circle.

Examples

function setup() { displayMode(NORMAL); p = new Parameter({type: "number", title: "Y Position", min: 0, max: HEIGHT, initial: HEIGHT/2, step: 1}); } function draw() { background(0); fill(255,0,0); ellipse( WIDTH/2, p.value, 20 ); }

The touched() function top ↑

The touched function deals with any mouse or touch events (specifically, those that occur on the canvas). After each time the draw function is called, the touched function is called for each mouse or touch event that occured during the previous draw function. It is passed one parameter, which is an object consisting of lots of information about the event.

A touch object has the following information:

Examples

var touchpt; var msg; function setup() { displayMode(NORMAL); p = new Parameter({type: "number", title: "Y Position", min: 0, max: HEIGHT, initial: HEIGHT/2, step: 1}); touchpt = new Vec2(0,0); msg = ""; new Parameter({type: "watch", watch: function() {return msg}}); } function draw() { background(0); fill(255,0,0); ellipse( WIDTH/2, p.value, 20 ); fill(255,255,0); ellipse(touchpt,50); text(msg,WIDTH/2,100); } function touched(t) { touchpt = new Vec2(t.x,t.y); } function key(k) { if (k.state == ENDED) { msg += k.key; } }

The key() function top ↑

The key function deals with any keyboard events (specifically, those that occur on the canvas). After each time the draw function is called, the key function is called for each keyboard event that occured during the previous draw function. It is passed one parameter, which is an object consisting of lots of information about the event.

Examples

var touchpt; var msg; function setup() { displayMode(NORMAL); p = new Parameter({type: "number", title: "Y Position", min: 0, max: HEIGHT, initial: HEIGHT/2, step: 1}); touchpt = new Vec2(0,0); msg = ""; new Parameter({type: "watch", watch: function() {return msg}}); } function draw() { background(0); fill(255,0,0); ellipse( WIDTH/2, p.value, 20 ); fill(255,255,0); ellipse(touchpt,50); text(msg,WIDTH/2,100); } function touched(t) { touchpt = new Vec2(t.x,t.y); } function key(k) { if (k.state == ENDED) { msg += k.key; } }

Drawing

background( colour ) top ↑

Syntax

background( colour );

Clears the background to the specified colour. You should generally call this at the start of your draw() function in order to clear the contents of the previous frame.

colour

a colour specification, see the colour type for details.

Examples

function draw() { // Dark blueish background background(0, 50, 70); // Do some drawing }

ellipse( x, y, width, height ) top ↑

Syntax

ellipse( x, y, diameter ); ellipse( x, y, width, height );

Draws an ellipse centered at x, y with horizontal and vertical dimensions specified by width and height. The ellipseMode() function sets how these parameters are interpreted. Use fill() to set the colour of an ellipse and stroke() to set its outline colour.

If only the width is specified, this is treated as the ellipse diameter (or radius, if ellipseMode( RADIUS ) is used) and the result is a circle. The interpretation of an ellipse's x, y, width and height parameters can be specified using the ellipseMode() function. ellipseMode() is set to CENTER by default.

x

x-coordinate of the ellipse

y

y-coordinate of the ellipse

width

width of the ellipse

height

height of the ellipse

circle( x, y, radius ) top ↑

Syntax

circle( x, y, radius );

Draws a circle centered at x, y with radius radius. The ellipseMode() function sets how these parameters are interpreted. Use fill() to set the colour of an circle and stroke() to set its outline colour. The interpretation of a circles x, y, and radius parameters can be specified using the ellipseMode() function. ellipseMode() is set to CENTER by default.

x

x-coordinate of the circle

y

y-coordinate of the circle

radius

radius of the circle

rect( x, y, width, height ) top ↑

Syntax

rect( x, y, width, height );

Draws a rectangle with its lower-left corner positioned at x, y and sized at width, height. Use fill() to set the colour of a rectangle and stroke() to set the outline colour.

The interpretation of a rectangle's x, y, width and height parameters can be specified using the rectMode() function. rectMode() is set to CORNER by default.

x

x-coordinate of the lower-left corner

y

y-coordinate of the lower-left corner

width

width of the rectangle

height

height of the rectangle

polygon( vertices ) top ↑

Syntax

polygon( vertices );

Draws a polygon with the specified vertices. Use fill() to set the colour of a polygon and stroke() to set the outline colour.

vertices

a list of vertices of the polygon, either as Vec2s or as x and y coordinates.

Examples

background(100, 120, 160); polygon(200,100,200,200,300,100);

polyline( vertices ) top ↑

Syntax

polyline( vertices );

Draws a series of lines through with the specified points. Use fill() to set the colour of a polyline and stroke() to set the outline colour. The difference between a polyline and a polygon is that a polygon is a closed shape, whereas a polyline does not automatically join up.

vertices

a list of vertices of the polyline, either as Vec2s or as x and y coordinates.

Examples

background(100, 120, 160); polyline(200,100,200,200,300,100);

text( string, x, y ) top ↑

Syntax

text( string, x, y );

Draws text at the given x, y location. You can set the font used by text() with the font() function. Text appearance can be further configured by using the fontSize() and fill() functions.

You can change the alignment and wrapping of text by using textAlign() and textWrapWidth(). If textWrapWidth() is set to 0 (the default) text will be drawn on one line. If textWrapWidth() is set to a value greater than 0 the text will word-wrap if it exceeds the width specified by textWrapWidth()

By default the x and y parameters set the location of the center of the text, the origin mode can be set using the textMode() and textValign() functions. Text colour can be changed with the fill() function.

If you need to get the dimensions of a string in the current style, see the textSize function documentation.

string

the text string that you would like to draw onto the screen

x

x-coordinate of the center of the text (this can be changed with textMode)

y

y-coordinate of the center of the text (this can be changed with textMode)

Examples

background(100, 120, 160); font("Georgia"); fill(255); fontSize(20); textWrapWidth(70); text("Hello World!", WIDTH/2, HEIGHT/2);

line( x1, y1, x2, y2 ) top ↑

Syntax

line( x1, y1, x2, y2 );

Draws a line between the two points specified by x1,y1 and x2,y2 (either or both can specified by a Vec2). A line's colour can be set with the stroke() function and its width can be set with the strokeWidth() function. A line's cap style can be changed with the lineCapMode() function.

x1

x-coordinate of the first point

y1

y-coordinate of the first point

x2

x-coordinate of the second point

y2

y-coordinate of the second point

Examples

function draw() { background(128); stroke(255); line(10, 10, 80, 80); }

arc( x, y, radius, startAngle, endAngle, clockwise ) top ↑

Syntax

arc( x, y, radius, startAngle, endAngle, clockwise );

Draws an arc as specified by the parameters. It starts at the point x,y and has radius radius. The span of the arc is specified by the angles startAngle and endAngle. The first is the initial angle. If arcMode is set to ABSOLUTE then endAngle is the final angle, otherwise it is the angle subtended by the arc (sometimes referred to as the delta angle). The final argument, a boolean, determines whether the arc is drawn anti-clockwise (true or blank) or clockwise (false). Angles are specified in degrees.

x

x-coordinate of the start of the arc

y

y-coordinate of the start of the arc

radius

radius of the arc

startAngle

starting angle of the arc

endAngle

ending or delta angle of the arc

clockwise

boolean to decide whether the arc is drawn clockwise or anti-clockwise

Examples

function draw() { background(128); stroke(255); arc(200, 10, 50, 20, 180); }

bezier( x1, y1, x2, y2, x3, y3, x4, y4 ); top ↑

Syntax

bezier( x1, y1, x2, y2, x3, y3, x4, y4 );

Draws a cubic bezier as specified by the parameters. It starts at the point x1,y1, ends at x4,y4, and has control points x2,y2 and x3,y3. The points can be Vec2s. If bezierMode is ABSOLUTE then the control points are the actual points, if bezierMode is RELATIVE then the control points are relative to the respective endpoints.

x1

x-coordinate of the start of the curve

y1

y-coordinate of the start of the curve

x2

x-coordinate of the first control point

y2

y-coordinate of the first control point

x3

x-coordinate of the second control point

y3

y-coordinate of the second control point

x4

x-coordinate of the end of the curve

y4

y-coordinate of the end of the curve

Examples

function draw() { background(128); stroke(255); bezier(200, 100, 200, 200, 300, 100, 300, 200 ); }

Transform

translate( x, y ) top ↑

Syntax

translate( x, y );

Translates all subsequent drawing operations by the specified x and y values. Translations are cumulative, so a call to translate( 50, 0 ) followed by a call to translate( 10, 10 ) will translate all subsequent drawing operations by 60, 10.

x

amount of horizontal translation, in pixels

y

amount of vertical translation, in pixels

rotate( angle ) top ↑

Syntax

rotate( angle ); rotate( angle, x, y );

Specifies an amount of rotation (in degrees) to apply to all subsequent drawing. All subsequent drawing functions will be rotated by angle value specified in this function. Rotations are cumulative, so calling rotate(30) followed by rotate(20) has the same effect as rotate(50).

rotate() can also be called with a point, defined by the x, and y parameters. This allows rotation to occur about an arbitrary point.

angle

amount of rotation in degrees

x

float, x value for the centre of the rotation

y

float, y value for the centre of the rotation

scale( x, y ) top ↑

Syntax

scale( amount ); scale( x, y );

Specifies an amount of scale to apply to all drawing. All subsequent drawing functions will be scaled by the x and y values specified in this function. Scale values are specified as a scalar multipliers, for example, scale(2.0, 2.0) will double the x and y dimensions of subsequent drawing commands. scale() is cumulative, so calling scale(0.5) followed by scale(0.5) will scale all subsequent drawing operations by 0.25 (i.e., one quarter of their original size).

amount

uniform amount of scale to apply horizontally and vertically. Applies on both axis, x and y.

x

amount of scale to apply on the x axis (horizontal)

y

amount of scale to apply on the y axis (vertical)

Advanced Transform

composeTransformation( transformation ) top ↑

Syntax

composeTransformation( transformation );

Composes the transformation specified by transformation with the current model transformation. The current model transformation represents the world transform, this is the same transformation used in pushTransformation and popTransformation operations.

transformation

transformation, the transformation to compose with the current world transform

modelTransformation() top ↑

Syntax

modelTransformation(); modelTransformation( transformation );

When called with no arguments, returns a transformation containing current world transformation. When called with a transformation argument, sets the current world transformation to the given transformation.

transformation

transformation, the transformation to set as the current world transform

Returns

The current model transformation when called with no arguments

Style

Colour top ↑

Syntax

colour.r colour.g colour.b colour.a myColour = new Colour( 255, 0, 0, 255 ); //red myColour = new Colour( "#ff0000" ); //red myColour = new Colour( "#f00" ); //red myColour = new Colour( "#f" ); //white myColour = new Colour( "rgb(255,0,0)"); //red myColour = new Colour( "rgba(255,0,0,255)"); //red myColour = new Colour( "Red"); //red myColour = new Colour( "Red4"); //dark red

This type represents a colour with transparency information. You can provide this type as arguments to the style functions fill(), tint(), stroke(), and background(). You can specify the colour in a variety of ways, either by specifying the red, green, blue, and alpha components directly or by passing a string describing the colour in one of the CSS formats or as an SVG or X11 named colour.

r

int, the red component of this colour from 0 to 255

g

int, the green component of this colour from 0 to 255

b

int, the blue component of this colour from 0 to 255

a

int, the alpha component of this colour from 0 to 255

Examples

--Fill with red c = new Colour( 255, 0, 0 ); fill( c );

Colour.blend( c ) top ↑

Syntax

c1 = new Colour( 0, 0, 0, 128 ) c2 = new Colour( 255, 255, 255, 255 ) c3 = c1.blend( c2 )

This method computes a colour by blending two colour types. Colours are blended based on the first colour's alpha value. The blend amount is determined by the alpha value of the colour invoking this method.

c

colour, compute the blending between this colour and c

Returns

Colour computed by blending this colour and c

Colour.mix( c, amount ) top ↑

Syntax

c1 = new Colour( 255, 0, 0, 255 ); c2 = new Colour( 0, 255, 0, 255 ); c3 = c1.mix( c2, 0.5 );

This method computes a colour by mixing two colour types linearly. Colours are blended based on the specified mix value, amount. A value of 0.5 for amount will generate a colour that is half way between the two input colours.

c

colour, compute the mixing between this colour and c

amount

scalar, amount of contribution from either colour. A value of 0.0 will result in the starting colour, and 1.0 will result in the destination colour.

Returns

Colour computed by mixing this colour and c by amount

blendMode( MODE ) top ↑

Sets the blend mode for all further drawing. The blend mode decides how new drawing operations are blended with underlying pixels. See the MDN article on blendmodes for details.

mode

one of:

sourceOver:

sourceIn

sourceOut

sourceAtop

destinationOver

destinationIn

destinationOut

destinationAtop

lighter

copy

xor

multiply

screen

overlay

darken

lighten

colourDodge

colourBurn

hardLight

softLight

difference

exclusion

hue

saturation

colour

luminosity

ellipseMode( MODE ) top ↑

Syntax

ellipseMode(); ellipseMode(CENTER|RADIUS|CORNER|CORNERS);

Sets the origin of the ellipses and circles drawn with the ellipse() and circle() functions. The default is ellipseMode( CENTER ).

mode

either CENTER, RADIUS, CORNER or CORNERS

CENTER: x, y specifies the center of the ellipse, w, h specify its x and y diameters.

RADIUS: x, y specifies the center of the ellipse, w, h specify its x and y radii.

CORNER: x, y specifies the lower left corner of the ellipse, w, h specify the size of its x and y diameters. CORNERS: x, y sets the lower left coordinate of the ellipse's bounding box. w, h sets the upper right coordinate of the ellipse's bounding box.

Returns

The current ellipse mode if called without arguments. Returns nothing if called with arguments.

rectMode( MODE ) top ↑

Syntax

rectMode() rectMode(CENTER|RADIUS|CORNER|CORNERS)

Sets the origin of the rectangles drawn with the rect() function. The default is rectMode( CORNER ).

mode

either CENTER, RADIUS, CORNER or CORNERS

CENTER: x, y specifies the center of the rectangle, w, h specifies the rectangle's width and height.

RADIUS: x, y specifies the center of the rectangle, w, h specifies half the rectangle's width and height.

CORNER: x, y specifies the lower left corner of the rectangle, w and h specify the rectangle's width and height.

CORNERS: x, y sets the lower left coordinate of the rectangle's bounding box. w, h sets the upper right coordinate of the rectangle's bounding box.

Returns

The current rect mode if called without arguments. Returns nothing if called with arguments.

arcMode( MODE ) top ↑

Syntax

arcMode(); arcMode(ABSOLUTE|RELATIVE);

Sets how the final angle is interpreted in the arc() function.

mode

either ABSOLUTE or RELATIVE ABSOLUTE: the endAngle is the final angle of the arc RELATIVE: the endAngle is the angle swept out by the arc

Returns

The current arc mode if called without arguments. Returns nothing if called with arguments.

bezierMode( MODE ) top ↑

Syntax

bezierMode(); bezierMode(ABSOLUTE|RELATIVE);

Sets how the control points are interpreted in the bezier() function.

mode

either ABSOLUTE or RELATIVE ABSOLUTE: the control points are the actual points RELATIVE: the control points are relative to their respective endpoints

Returns

The current bezier mode if called without arguments. Returns nothing if called with arguments.

textMode( MODE ) top ↑

Syntax

textMode() textMode( CENTER|CORNER )

Sets the origin of text drawn with the text() function. The default is textMode( CENTER ).

mode

either CENTER or CORNER

CENTER: x, y specifies the center of the text.

CORNER: x, y specifies the lower left corner of the text.

Returns

The current text mode if called without arguments. Returns nothing if called with arguments.

lineCapMode( MODE ) top ↑

Syntax

lineCapMode() lineCapMode( ROUND | SQUARE | PROJECT )

Sets the style of the line caps drawn with the line() function. The default is lineCapMode( ROUND ). Note that lineCapMode() only has an effect if smooth() is set.

mode

either ROUND, SQUARE or PROJECT

ROUND: line ends are rounded with circles

SQUARE: line ends are squared off at the end points

PROJECT: line ends are squared off, but project out as far as if they were rounded

Examples

background(40, 40, 50) smooth() stroke(255) strokeWidth(15) translate(WIDTH/2, HEIGHT/2) lineCapMode(ROUND) line(-30, -30, -30, 30) lineCapMode(SQUARE) line(0, -30, 0, 30) lineCapMode(PROJECT) line(30, -30, 30, 30)

Returns

The current line cap mode if called without arguments. Returns nothing if called with arguments.

fill( red, green, blue, alpha ) top ↑

Syntax

fill() fill( gray ) fill( gray, alpha ) fill( red, green, blue ) fill( red, green, blue, alpha ) fill( colour )

Sets the colour used to fill shapes drawn with the ellipse() and rect() functions. Also sets the colour of text drawn with the text() function.

gray

int from 0 to 255, specifies value between white and black

alpha

int from 0 to 255, specifies opacity of the fill

red

int from 0 to 255, specifies red amount of the fill

green

int from 0 to 255, specifies green amount of the fill

blue

int from 0 to 255, specifies blue amount of the fill

colour

a value of the colour datatype

Returns

Four values (r,g,b,a) representing the current fill colour if called without arguments. Returns nothing if called with arguments.

noFill() top ↑

Syntax

noFill()

Sets the colour of the fill to completely transparent.

stroke( red, green, blue, alpha ) top ↑

Syntax

stroke() stroke( gray ) stroke( gray, alpha ) stroke( red, green, blue ) stroke( red, green, blue, alpha ) stroke( colour )

Sets the colour used to outline the shapes drawn with the ellipse() and rect() functions. Also sets the colour of lines drawn with the line() function.

gray

int from 0 to 255, specifies value between white and black

alpha

int from 0 to 255, specifies opacity of the stroke

red

int from 0 to 255, specifies red amount of the stroke

green

int from 0 to 255, specifies green amount of the stroke

blue

int from 0 to 255, specifies blue amount of the stroke

colour

a value of the colour datatype

Returns

Four values (r,g,b,a) representing the current stroke colour if called without arguments. Returns nothing if called with arguments.

strokeWidth( width ) top ↑

Syntax

strokeWidth() strokeWidth( width )

Sets the width of the outline of shapes drawn with the ellipse() and rect() functions. Also sets the width of lines drawn with the line() function.

width

int or float, the width in pixels of the stroke

Returns

The current stroke width if called without arguments. Returns nothing if called with arguments.

noStroke() top ↑

Syntax

noStroke()

Sets the stroke width to zero.

font( name ) top ↑

Syntax

font() font( name )

This sets the current font to the font specified by name. If no argument is given font() returns the current font. The default font is "Helvetica".

name

string, the name of the font to use. A list of available fonts can be found by tapping on the font() function in the code editor.

Returns

The current font if called without arguments. Returns nothing if called with arguments.

fontSize( size ) top ↑

Syntax

fontSize() fontSize( size )

This sets the current font size to the size specified by size. If no argument is given fontSize() returns the current font size. The default font size is 17 points.

size

float, the size of the font (in points). Must be greater than 0.0.

Returns

The current font size if called without arguments. Returns nothing if called with arguments.

textAlign( ALIGN ) top ↑

Syntax

textAlign() textAlign( LEFT|CENTER|RIGHT )

This sets the horizontal alignment of text rendered with the text() function. This is generally used in conjunction with textWrapWidth() to produce multi-line, word-wrapped text aligned to the LEFT, CENTER or RIGHT. If called without arguments this function returns the current text alignment. The default text alignment is textAlign( LEFT ).

ALIGN

Can be LEFT, CENTER or RIGHT

Returns

The current text alignment if called without arguments. Returns nothing if called with arguments.

textValign( ALIGN ) top ↑

Syntax

textValign() textValign( BOTTOM|BASELINE|CENTRE|TOP )

This sets the vertical alignment of text rendered with the text() function. If called without arguments this function returns the current text alignment. The default text alignment is textValign( BASELINE ).

ALIGN

Can be BOTTOM, BASELINE, CENTRE, or TOP

Returns

The current vertical text alignment if called without arguments. Returns nothing if called with arguments.

Text Metrics

textSize( string ) top ↑

Syntax

width = textSize( string ) width, height = textSize( string )

This function returns the width of the specified string when rendered with the current font size and style. You can use this to, for example, render a button behind a piece of text, position text within a speech bubble, and so on.

string

string, the string to measure

Examples

background(100, 120, 160); font("Georgia"); fontSize(20); textWrapWidth(70); // Get the width of our string w = textSize("Hello World!"); // Draw a box behind our text fill(120,0,40); strokeWidth(2); rectMode(CENTER); rect(WIDTH/2,HEIGHT/2,w+15,h+15); fill(255); text("Hello World!",WIDTH/2,HEIGHT/2);

Returns

width and height of the text string when rendered with the current font size and style.

Transform Management

pushTransformation() top ↑

Syntax

pushTransformation()

The pushTransformation() function saves any transformations that have been made and pushes a copy of them onto the top of the stack. You can then perform further transforms (translations, rotations and scales), perform drawing operations, and return to the previous transformation by calling popTransformation(). You can nest calls to pushTransformation() and popTransformation() for more complex object placement.

The following transform calls are preserved when using pushTransformation() and popTransformation(): translate(), rotate(), scale()

popTransformation() top ↑

Syntax

popTransformation()

The popTransformation() function saves any transformations that have been made and pushes a copy of them onto the top of the stack. You can then perform further transforms (translations, rotations and scales), perform drawing operations, and return to the previous transformation by calling popTransformation(). You can nest calls to pushTransformation() and popTransformation() for more complex object placement.

The following transform calls are preserved when using pushTransformation() and popTransformation(): translate(), rotate(), scale()

resetTransformation() top ↑

Syntax

resetTransformation()

This function resets all transformation. It replaces the current transform transformation with the identity transformation. This effectively repositions all drawing at 0, 0, with no rotation and scaling.

Style Management

pushStyle() top ↑

Syntax

pushStyle()

The pushStyle() function saves the current graphics style and pushes a copy of the current style onto the top of the stack. You can then modify the style, perform drawing operations, and return to the previous style by calling popStyle(). You can nest calls to pushStyle() and popStyle() in order to provide more control.

Styles set with the following functions are preserved when using pushStyle() and popStyle(): fill(), noFill(), stroke(), noStroke(), tint(), noTint(), strokeWidth(), lineCapMode(), ellipseMode(), rectMode(), spriteMode(), smooth(), noSmooth(), font(), fontSize(), textAlign(), textMode() and textWrapWidth()

popStyle() top ↑

Syntax

popStyle()

The pushStyle() function saves the current graphics style and pushes a copy of the current style onto the top of the stack. You can then modify the style, perform drawing operations, and return to the previous style by calling popStyle(). You can nest calls to pushStyle() and popStyle() in order to provide more control.

Styles set with the following functions are preserved when using pushStyle() and popStyle(): fill(), noFill(), stroke(), noStroke(), tint(), noTint(), strokeWidth(), lineCapMode(), ellipseMode(), rectMode(), spriteMode(), smooth(), noSmooth()

resetStyle() top ↑

Syntax

resetStyle()

Calling resetStyle() will reset all style parameters to their default values. This will effect whatever style is currently on the top of the stack.

Styles set with the following functions are reset when using resetStyle(): fill(), noFill(), stroke(), noStroke(), tint(), noTint(), strokeWidth(), lineCapMode(), ellipseMode(), rectMode(), spriteMode(), smooth(), noSmooth()

Parameters

Overview of Parameters top ↑

Parameters are ways to elicit information from the user. A parameter defines a widget in the parameters panel (on the left of the browser window) which the user can interact with at any time during the execution of the script. To create parameter, you write:

p = new Parameter(options);

where options specifies the type and various options of the parameter. You would generally do this in the setup function.

All parameters except the action parameter have a value which can be accessed by the value attribute of the newly created parameter. Changing this value doesn't update the widget, for that you have to use:

p.setValue(value);

All parameters can be passed a callback function which is called whenever the value of the parameter is changed by the user. The callback function will be passed the new value.

The different types of parameter are:

  • number
  • text
  • boolean
  • select
  • colour
  • action
  • watch

("watch" isn't technically a parameter but it operates on a similar principle so is included here.)

Parameter Number top ↑

Syntax

p = new Parameter({type: "number", title: "Enter a number", value: 3, min: 1, max: 5, step: .5, callback: function(n) {print(n)}});

This parameter creates a visual slider in the parameter panel that can be used to get a number from the user. When you adjust the slider in the viewer, the variable will be set appropriately. The three parameters, min, max, and step allow you to set the minimum, maximum, and step value of your parameter respectively. If an initial value is not specified, then the parameter takes on the minimum value initially. If no minimum or maximum values are specified, the parameter uses the range [0, 1] with step value 0.1. If the minimum and maximum are specified but the step value is not, the step value is taken to be 1.

title

string, the text displayed above the slider

min

int or float, specifies the minimum value that your parameter can take

max

int or float, specifies the maximum value that your parameter can take

slider

int or float, specifies the step value for the slider

value

int or float, specifies the initial, or starting, value of the parameter

callback

function, this function will be called whenever the parameter is changed, it will be given the parameter value as an argument

Examples

var p; function setup() //Creates a number parameter p = new Parameter({type: "number", title: "Radius", min: 50, max: 300, step: 1, value: 100}); end function draw() background(128); ellipseMode(RADIUS); ellipse(WIDTH/2, HEIGHT/2, p.value); end

Parameter Colour top ↑

Syntax

p = new Parameter({type: "colour", title: "Pick a colour", value: new Colour("red")});

This function creates a visual colour sample in the viewer that can be used to get a colour from the user. Note that this uses the HTML5 colour picker. In some browsers, there is no obvious Select button and the picker should be dismissed by clicking the X button on its window.

text

string, the text displayed by the colour picker

value

colour, specifies the initial colour

callback

function, this function will be called whenever the parameter is changed, it will be given the new colour value as an argument

Examples

var fc, sc; function setup() { // Creates a colour parameter variable called fc // make it red by default fc = new Parameter({type: "colour", title: "Fill Colour", value: new Colour('red')}); // Creates a global colour parameter variable called sc // make it white by default sc = new Parameter({type: "colour", title: "Stroke Colour", value: new Colour('white')}); } function draw() { background(128); strokeWidth(10); // Set our colours using the parameter values stroke(sc.value); fill(fc.value); ellipse(WIDTH/2, HEIGHT/2, 300); }

Parameter Select top ↑

Syntax

p = new Parameter({type: "select", title: "Make a choice", options: ["a", "b", "c"], value: "a"});

This function creates a drop-down list in the viewer that can be used to get a choice from the user.

title

string, the text displayed above the option list

options

array, specifies the list of options

value

string, specifies the initial choice

callback

function, this function will be called whenever the parameter is changed, it will be given the new colour value as an argument

Examples

var opt; function setup() { opt = new Parameter({type: "select", title: "Make a choice", options: ["a","b","c"], value: "a"}); }

Parameter Boolean top ↑

Syntax

b = new Parameter({type: "boolean", title: "Choose", value: true, callback: function(b) {}});

This function creates a visual switch in the viewer that can be used to get a boolean from the user.

title

string, the text shown in the parameter pane

value

boolean, specifies the initial value of the boolean parameter

callback

function, this function will be called whenever the parameter is changed, it will be given the parameter value as an argument

Examples

var b; function setup() { // Creates a simple switch that prints when changed b = new Parameter({type: "boolean", title: "My Switch", value: true, callback: switchChanged}); } function switchChanged( value ) { print( "My Switch changed to " + value ); }

Parameter Text top ↑

Syntax

b = new Parameter({type: "text", title: "Title", value: "Value", callback: function(t) {print(t)}});

This function creates a visual text box in the viewer. You can use this to get some text from the user.

title

string, the text to display above the input field

value

string, specifies the initial value of the text parameter

callback

function, this function will be called whenever the parameter is changed, it will be given the parameter value as an argument

Examples

var txt; function setup() { // Creates a simple switch that prints when changed txt = new Parameter({type: "text", title: "Write some text", value: "Hello World!", callback: textChanged}); } // Print our text parameter in upper-case function textChanged( value ) { print( string.upper(value) ) }

Parameter Action top ↑

Syntax

new Parameter({type: "action", title: "Title", callback: function() {}});

This function creates a visual button in the viewer sidebar. Pressing the button will call the function defined by callback. This parameter has no value, so there is generally no need to assign it to a variable.

title

string, this text will be displayed above the button

callback

function, this function will be called whenever the parameter is changed, it will be given the parameter value as an argument

Examples

function setup() { // Creates a button to clear the output new Parameter({type: "action", title: "Clear Output", callback: output.clear}); }

Parameter Watch top ↑

Syntax

Parameter Watch

This function allows you to monitor the return value of a javascript function within the viewer.

title

string, the title shown above the output

watch

function, the function whose return value to show

Examples

function setup() { // Shows the elapsed time in the viewer new Parameter({type: "watch", title: "Elapsed Time", watch: function() {return ElapsedTime;}); }

parameters.clear() top ↑

Syntax

parameters.clear()

This function clears the parameter list of all parameter widgets and watch values. You can then re-add parameters using the parameter group of functions.

Vectors

Vec2 top ↑

Syntax

Vec2.x Vec2.y myVec = my Vec2( 2.5, 10.0 )

This type represents a 2D vector.

x

float, the x component of this vec2

y

float, the y component of this vec2

Examples

// Some vector operations v1 = new Vec2( 1, 1 ) v2 = new Vec2( 4, 2 ) // Angle between v1.angleBetween( v2 ) // Adding v3 = v1.add(v2) // Multiplying v4 = v1.multiply(5.0) // Rotating by 45 degrees v5 = v1.rotate(math.rad(45))

Vec2.add( v ) top ↑

Syntax

v1 = new Vec2( 1, 1 ) x = v1.add( v )

This method returns the sum of two Vec2 types

v

compute the sum of this Vec2 and v

Returns

Sum of this Vec2 and v

Vec2.increment( v ) top ↑

Syntax

v1 = new Vec2( 1, 1 ) v1.increment( v )

This method increments a Vec2 by another. It modifies the calling object in place.

v

increment this Vec2 by v

Returns

This Vec2 incremented by v

Vec2.subtract( v ) top ↑

Syntax

v1 = new Vec2( 1, 1 ) x = v1.subtract( v )

This method returns the result of subtracting one Vec2 from another

v

compute the result of subtracting one Vec2 from another

Returns

The result of subtracting one Vec2 from another

Vec2.decrement( v ) top ↑

Syntax

v1 = new Vec2( 1, 1 ) v1.decrement( v )

This method decrements a Vec2 by another. It modifies the calling object in place.

v

decrement this Vec2 by v

Returns

Decrement this Vec2 by v

Vec2.multiply( v ) top ↑

Syntax

v1 = new Vec2( 1, 1 ) x = v1.multiply( v )

This method returns the product of a Vec2 and a number or another Vec2s. In the latter case, the Vec2s are treated as complex numbers.

v

compute the product of this Vec2 and v

Returns

product of this Vec2 and v

Vec2.multiplyBy( v ) top ↑

Syntax

v1 = new Vec2( 1, 1 ) v1.multiplyBy( v )

This method multiplies this Vec2 by either a number or another Vec2, modifying the calling object.

v

Multiply this Vec2 by v

Returns

Product between this Vec2 and v

Vec2.divide( v ) top ↑

Syntax

v1 = new Vec2( 1, 1 ) x = v1.divide( v )

This method returns the result of dividing this Vec2 by either a number or another Vec2. In the latter case, the division is that of complex numbers.

v

compute the result of dividing this Vec2 by v

Returns

The result of dividing this Vec2 by v

Vec2.divideBy( v ) top ↑

Syntax

v1 = new Vec2( 1, 1 ) x = v1.divideBy( v )

This method divides this Vec2 by either a number or another Vec2. In the latter case, the division is that of complex numbers. This modifies the calling object.

v

compute the result of dividing this Vec2 by v

Returns

The result of dividing this Vec2 by v

Vec2.unminus( ) top ↑

Syntax

v1 = new Vec2( 1, 1 ) x = v1.unminus( )

This method returns the negative of this Vec2

Returns

The negative of this Vec2

Vec2.negate( ) top ↑

Syntax

v1 = new Vec2( 1, 1 ) v1.negate()

This method negates this Vec2, modifying the calling object

Returns

The negative of this Vec2

Vec2.equals( v ) top ↑

Syntax

v1 = new Vec2( 1, 1 ) x = v1.equals( v )

This method compares this Vec2 with another

v

test two Vec2s for equality

Returns

True if the Vec2s are equal, false if not

Vec2.normalize() top ↑

Syntax

v1 = new Vec2( 5, 5 ) v1 = v1.normalize()

This method returns a normalized version of the vector

Returns

Normalized version of this Vec2

Vec2.renormalize() top ↑

Syntax

v1 = new Vec2( 5, 5 ) v1.renormalize()

This method returns a normalized version of the vector, modifying the calling object

Returns

Normalized version of this Vec2

Vec2.dist( v ) top ↑

Syntax

v1 = new Vec2( 1, 1 ) x = v1.dist( new Vec2(2, 2) )

This method returns the distance between two Vec2 types

v

compute the distance between this Vec2 and v

Returns

Distance between this Vec2 and v

Vec2.distSqr( v ) top ↑

Syntax

v1 = new Vec2( 1, 1 ) x = v1.distSqr( new Vec2(2, 2) )

This method returns the squared distance between two Vec2 types

v

compute the squared distance between this Vec2 and v

Returns

Squared distance between this Vec2 and v

Vec2.len() top ↑

Syntax

v1 = new Vec2( 2, 1 ) x = v1.len()

This method returns the length of a Vec2

Returns

Length of this Vec2

Vec2.lenSqr() top ↑

Syntax

v1 = new Vec2( 2, 1 ) x = v1.lenSqr()

This method returns the squared length of a Vec2

Returns

Squared length of this Vec2

Vec2.cross( v ) top ↑

Syntax

v1 = new Vec2( 1, 1 ) v2 = v1.cross( new Vec2(2, 2) )

This method returns the cross product between two Vec2 types

v

compute the cross product of this Vec2 and v

Returns

Cross product of this Vec2 and v

Vec2.rotate( angle ) top ↑

Syntax

v1 = new Vec2( 1, 1 ) v2 = v1.rotate( math.rad(45) )

This method returns a rotated copy of a Vec2 type. The angle is assumed to be degrees.

angle

float, rotate this vector by angle in degrees

Returns

Rotated version of this Vec2

Vec2.rotateBy( angle ) top ↑

Syntax

v1 = new Vec2( 1, 1 ) v1.rotateBy( 45 )

This method returns a rotated copy of a Vec2 type. The angle is assumed to be degrees. This method modifies the calling object.

angle

float, rotate this vector by angle in degrees

Returns

Rotated version of this Vec2

Vec2.rotate90() top ↑

Syntax

v1 = new Vec2( 1, 1 ) v2 = v1.rotate90()

This method returns a copy of a Vec2 type, rotated 90 degrees.

Returns

Rotated version of this Vec2

Vec2.rotateBy90() top ↑

Syntax

v1 = new Vec2( 1, 1 ) v1.rotateBy90()

This method returns a copy of a Vec2 type, rotated 90 degrees. This method modifies the calling object.

Returns

Rotated version of this Vec2

Vec2.angleBetween( v ) top ↑

Syntax

v1 = new Vec2( 1, 1 ) angle = v1.angleBetween( new Vec2(5, 2) )

This method returns the angle between this Vec2 and v in degrees.

v

compute the angle between this Vec2 and v

Returns

Angle between Vec2 and v in degrees

Vec2.angle( ) top ↑

Syntax

v1 = new Vec2( 1, 1 ) angle = v1.angle( )

This method returns the angle between this Vec2 and the x-axis in degrees.

v

compute the angle between this Vec2 and the x-axis

Returns

Angle between Vec2 and the x-axis in degrees

Constants

WIDTH top ↑

Syntax

WIDTH

This constant is set to the width of the screen in pixels.

Returns

Width of the screen in pixels

HEIGHT top ↑

Syntax

HEIGHT

This constant is set to the height of the screen in pixels.

Returns

Height of the screen in pixels

Variables

ElapsedTime top ↑

Syntax

ElapsedTime

Query this variable to get the current elapsed time, in seconds, while running your project.

Returns

Time in seconds since the start of running the project

DeltaTime top ↑

Syntax

DeltaTime

Query this variable to get the time elapsed, in seconds, since the last draw call while running your project.

Returns

Time in seconds since the start of the previous frame