Graphics

Reference ❯ Drawing Shapes, Styles and Positioning

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.

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.

function setup() {
    displayMode(STANDARD);
    parameter.number("Y Position", 'yposition', 0, 
              HEIGHT, HEIGHT/2,1);
}

function draw() {
    background(0);
    fill(255,0,0);
    ellipse( WIDTH/2, 
             parameters.yposition, 
             200 );
}

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 = colour( 255, 0, 0, 255 ); //red myColour = colour( "#ff0000" ); //red myColour = colour( "#f00" ); //red myColour = colour( "#f" ); //white myColour = colour( "rgb(255,0,0)"); //red myColour = colour( "rgba(255,0,0,255)"); //red myColour = colour( "Red"); //red myColour = 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().

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

s

a string specification of the colour, a wide variety of possible specifications are available, including SVG and X11 names

Examples

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

colour.blend( c ) top ↑

Syntax

c1 = colour( 0, 0, 0, 128 ) c2 = 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 = colour( 255, 0, 0, 255 ); c2 = 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 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()

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