0% found this document useful (0 votes)
131 views20 pages

Introduction To Generative Drawing: A Self-Paced Workbook

This document provides an introduction to generative drawing, both with and without using a computer. Generative drawing involves creating images by following a set of simple rules, either manually or through a computer program. The workbook will have readers create generative drawings manually and then translate their drawings into computer programs using p5.js. This allows for introducing randomness to produce different results each time. The goal is to learn basic programming concepts while focusing on the artistic aspects of generative drawing.

Uploaded by

gmcon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
131 views20 pages

Introduction To Generative Drawing: A Self-Paced Workbook

This document provides an introduction to generative drawing, both with and without using a computer. Generative drawing involves creating images by following a set of simple rules, either manually or through a computer program. The workbook will have readers create generative drawings manually and then translate their drawings into computer programs using p5.js. This allows for introducing randomness to produce different results each time. The goal is to learn basic programming concepts while focusing on the artistic aspects of generative drawing.

Uploaded by

gmcon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Table of Contents

What's This Workbook About?........................................................1


What is Generative Drawing?..........................................................2
Introduction to Generative Drawing Without a Computer.......................................4
Translating Our Drawing into Code.................................................5
Generative Drawing Generative Drawing with a Computer.............................................6
Getting to Know the p5.js Web Editor.............................................7
Functions and Variables...................................................................8
A Self-Paced Workbook Playing a Sketch...............................................................................9
Printing a Message to the Console Pane........................................10
Creating a Canvas..........................................................................11
Changing the Colour of the Canvas...............................................12
Drawing a Point.............................................................................13
Drawing a Line..............................................................................14
Drawing a Triangle........................................................................15
Drawing a Rectangle......................................................................16
Drawing an Ellipse.........................................................................17
Setting Colours...............................................................................18
Introducing Variability into the Sketches.......................................19
Varying the Placement of Your Circle............................................20
Controlling the Draw Loop............................................................21
Varying the Placement of Your Square..........................................22
Generative Drawing is about creating images Placing Shapes Anywhere on the Canvas......................................23
by following a set of simple rules, either with Varying the Placement and Shape of Your Triangle......................24
or without a computer! Preserving the Shape of Your Triangle..........................................25
Varying the Size of Your Circle.....................................................26
Varying the Size of Your Square....................................................27
Prepared by Adam Herst
www.adamherst.art Varying the Colour of Your Shapes................................................28
[email protected] Creating a Custom Shape...............................................................30
Looping Through the Variations....................................................31
Preparing Your Sketch to Share.....................................................32
Sharing Your Sketch.......................................................................33
What's Next?..................................................................................34
2020-02-07 The Completed Sketch...................................................................35
What's This Workbook About? What is Generative Drawing?
This workbook is about art first and computer programming Generative drawing is one type of generative art:
second: Generative art refers to art that in whole or in part has
• If you like to draw, you should enjoy the activities in this been created with the use of an autonomous system.
workbook An autonomous system in this context is generally one
• If you don't know how to write computer programs, don't that is non-human and can independently determine
worry; you don't need any previous programming features of an artwork that would otherwise require
experience to complete the activities in this workbook decisions made directly by the artist.
https://en.wikipedia.org/wiki/Generative_art
We are going to ...
We're going to create drawings using two autonomous systems:
• Look at some examples of generative drawing, created both
with and without a computer • a written set of rules

• Create a generative drawing without using a computer • a computer program

• Use the web editor available for p5.js, a programming The features of our artwork that the autonomous systems will
language developed for artists, to write computer programs determine are:

• Translate our generative drawings into p5.js programs • location

• Introduce randomization into the programs to produce a • size


different sketch each time the program is run • colour
• Share our sketches over the web Why Should We Use a Computer to Create Drawings?
We aren't going to ... After all, if your program can’t do anything more than
• Learn the intricacies of programming (but we are going to what you could do quicker, better, or more creatively
learn about a few very basic programming concepts) with a physical object, why bother using a computer at
all.
• Do a lot of math (but we are going to do a little bit) https://www.futurelearn.com/courses/creative-coding/2/steps/35887
Activities and Bonus Activities Generative drawing isn't new. Sol LeWitt's wall drawings are one
This workbook is activity based. Each of the activities builds on example of drawing with code without a computer:
the previous activity. At the end of the workbook, if you complete On a wall surface, any
all the activities, you will have a working p5.js program. A version continuous stretch of wall,
of the program is presented at the end of this booklet. using a hard pencil, place
fifty points at random.
Bonus activities are extra. You don't have to complete them. They
The points should be evenly
introduce more advanced concepts and point out some additional distributed over the area
capabilities of p5.js.

1 2
of the wall. All of the Generative Drawing Without a Computer
points should be connected
by straight lines. We'll use these materials to create a generative drawing without
using a computer:
https://observer.com/2012/10/here-are-the-instructions-for-sol-lewitts-1971-
wall-drawing-for-the-school-of-the-mfa-boston • one piece of paper
• one pencil
• three crayons of different colours
Activity: Create a Generative Drawing
Create a generative drawing by:
1. Using the pencil, draw a triangle anywhere on the paper
2. Still using the pencil, draw a circle somewhere in the
remaining space
3. Still using the pencil, draw a square somewhere in
whatever space is left
4. Choose a crayon and colour in one of the shapes
At his core he was a minimalist, so much so that most
5. Using one of the remaining crayons, colour in one of the
of his famous pieces were not even executed by him in
remaining shapes
person. He did not sell paintings on canvases, instead
he sold “codes” or procedures with specific 6. Using the third and last crayon, colour in the third and last
instructions that would then be implemented by a shape
draftsman, who was required to faithfully execute the Triangle, Square, Circle
instructions, but whose own hand and judgement led to
the final formal outcome of the work. In 1923 Wassily Kandinsky circulated a questionnaire
https://generativelandscapes.wordpress.com/2014/08/14/procedural-art-sol- at the Bauhaus, asking respondents to fill in a triangle,
lewitt-example-3-1 square, and circle with the primary colors of red,
yellow, and blue...He hoped to discover a universal
Vera Molnár began drawing with code using an "imaginary
correspondence between form and color, embodied in
machine" and only later began using a physical computer.
the equation red=square, yellow=triangle,
Activity: Sol LeWitt and Vera Molnár blue=circle.
Explore their work by: https://bookofthrees.com/triangle-square-circle-a-psychological-test/

1. Going to http://solvingsol.com/solutions/
2. Going to http://dada.compart-bremen.de/item/agent/14

3 4
Translating Our Drawing into Code Generative Drawing with a Computer
Now that we've created a generative drawing without using a p5.js is a JavaScript library for creative coding, with a
computer, we're going to get it ready to translate into a p5.js focus on making coding accessible and inclusive for
program to create generative drawings using a computer. artists, designers, educators, beginners, and anyone
Activity: Prepare the Coordinate Grid else!
https://p5js.org/
Using the pencil:
We can create sketches using p5.js in two ways:
1. Draw a square around your three shapes, the smaller the
better as long it contains all the shapes • by downloading and installing the software

2. Draw a line from the centre of the top of the square to the • by using the online p5.js web editor
centre of the bottom, dividing the sketch into half For this workbook, we're going to use the web editor.
3. Draw a line from the centre of the left side of the square to If you want to save your sketches or share your sketches via the
the centre of the right side, dividing the sketch into four p5.js editor website, you'll need to create an account:
quarters
• The only information you'll be asked to provide is your
4. Draw lines dividing each of the quarters into four squares email address and a password.
so that you have a grid of 16 squares
• If you don't want to sign up, you can still use the editor but
Your sketch should look something like this: won't be able to save your work in progress or to share the
sketch.
Activity: Create a p5.js Web Editor Account
To create an account:
1. Go to https://editor.p5js.org/
2. In the top right corner, click on Sign up
Bonus Activity: Download and Install the p5.js Software
If you don't want to use the p5.js editor you can download the p5.js
libraries and work locally with a code editor of your choice.
Follow the instructions at:
• https://p5js.org/download/
• https://p5js.org/get-started/

5 6
Getting to Know the p5.js Web Editor Functions and Variables
We'll be using these parts of the web editor: Functions and variables are basic programming concepts that we'll
need to know about when we write programs in p5.js:
1 • A function is a block of organized, reusable code that is
used to perform a single, related action.
2 • Variables are names given to computer memory locations
which are used to store values in a computer program.
p5.js provides built-in functions and variables that we'll use in our
sketches.
setup() and draw()
3
5 All of our sketches will use the built-in functions setup() and
draw():
• The setup() function is run once when the Start button is
pressed.
• The draw() function will run over and over until the Stop
4
button is pressed.
In general, function names are followed by parentheses.
Variables names are never followed by parentheses.
1 - Menu Bar Later in the workbook we will learn how to define our own
Used to save, open, share, and download sketches functions and variables.
2 - Control Bar Activity: Use the p5.js Online Reference
Contains the Start and Stop buttons used to control the sketch The p5.js website has an online reference to the built-in functions
and variables. Look up the explanations for setup() and draw():
3 - Edit pane
• Go to https://p5js.org/reference
Used to type in the p5.js statements that make up a sketch
• Enter the name of the variable or function you want to look
4 - Console pane
up in the search field at the top right of the screen
Used to display status and system messages
You might want to keep a browser window open to the p5.js
5 - Preview pane reference during the workbook.
Used to display the output of the sketch when it is played

7 8
Playing a Sketch Printing a Message to the Console Pane
We can play the sketch in the Edit pane by clicking on the Start If a sketch can't be played, messages about possible reasons why
button. The sketch will be drawn in the Preview pane. We can stop are shown in the Console pane. We can print our own messages to
the sketch by clicking on the Stop button. the Console pane using the p5.js built-in function:
Typing in p5.js Statements • print()
The Edit pane is used to type in the p5.js statements that will make print()
up the sketch. The print() function writes to the console area of your browser.
p5.js statements end with a semicolon. This function is often helpful for looking at the data a program is
The Edit pane is pre-filled with a skeleton of a p5.js sketch: producing.
function setup() { Activity: Print a Message to the Console pane
createCanvas(400, 400);
Print a message to the Console pane by:
}
1. In the Editor pane, after the createCanvas() statement,
function draw() { add the statement:
background(220);
} print('What colour is your circle?');

Starting and Stopping the Sketch Make sure to include the quotation marks around the string.
The Start button starts the sketch. The Stop button stops the sketch. 2. Press the Start button. The message is displayed in the
They are located on the Control Bar just above the Edit pane. Console pane.
Displaying the Sketch Comments
The Preview pane is located to the right of the Edit pane. It shows If a p5.js statement contains the characters //, any characters in the
the result of playing the sketch. statement after the // are ignored. Comments are useful to explain
what statements in a sketch do. The sample sketch at the end of the
Activity: Play the Skeleton Sketch
booklet uses comments to show where an activity comes from.
Play the skeleton sketch by:
Bonus Activity: Print a Message Multiple Times
1. Pressing the Start button to start the sketch. The sketch
Statements in the setup() function are executed once. Statements
should draw a gray square in the Preview pane.
in the draw() function are executed over and over until the Stop
2. Pressing the Stop button to stop the sketch. The gray square button is pressed. You can print a message multiple times by:
should disappear.
1. After the background() statement, add the statement:
print('Message number: ' + frameCount);
2. Press the Stop button to stop the sketch.

9 10
Creating a Canvas Changing the Colour of the Canvas
Before we can draw a sketch we need to create a canvas to draw The default background is transparent. We can change the colour
on. We create a canvas with the built-in function: with the built-in function:
• createCanvas() • background()
createCanvas() background()
The createCanvas() function creates a canvas element in the The background() function sets the color used for the background
document, and sets the width and height dimensions of it in pixels: of the p5.js canvas.
createCanvas(width, height); background(colour)
createCanvas() should be called only once at the start of • background() is typically used within draw() to clear the
setup. display window at the beginning of each frame
The skeleton setup() creates a default canvas to draw on: • It can be used inside setup() to set the background on the
createCanvas(400, 400); first frame of animation or if the background need only be
set once.
• the first 400 represents the width of the canvas in pixels
CSS colour strings
• the second 400 represents the height of the canvas in pixels
The background() function in the skeleton sketch sets the colour
Activity: Change the Size of the Canvas using a numeric value (220 represents a shade of grey):
Change the size of the canvas by using different values for the background(220);
width and height. Make the canvas 200 pixels wide and 600 pixels
high by: An easier way to specify a colour in p5.js is to use a CSS colour
string, for example:
1. Change the createCanvas() statement to: 'lightgrey'
createCanvas(200, 600);
Make sure to include the quotation marks around the string.
2. Click on the Start button to draw the new canvas.
Activity: Set the Background Colour Using a CSS String
3. Click on the Stop button to stop the sketch
Change the background to light grey by:
4. Change the createCanvas() statement back to:
1. Change the background() statement to:
createCanvas(400, 400);
background('lightgrey');
Make sure to change the canvas width and height back to the
original dimensions. We're going to need a 400x400 pixel Bonus Activity: Set the Background Using HSB Values
canvas for the activities that follow. You can also use HSB values to specify a colour.
1. Explore colorMode() in the p5.js online reference. Use it
to set the background to light grey using HSB values.

11 12
Drawing a Point Drawing a Line
p5.js has built-in functions to draw points and to change the width p5.js has a built-in function to draw a line:
of the stroke that draws a point, line, or the border around shapes: • line()
• point() line()
• strokeWeight() The line() function draws a line, a direct path between two points.
point() line(x1, y1, x2, y2);
The point() function draws a single pixel at the specified • x1 and y1 are the coordinates of the point to start the line
coordinate on the canvas:
• x2 and y2 are the coordinates of the point to end the line
point(x, y);
Activity: Draw a Grid on Your Sketch
X and Y are numbers that identify a location on the canvas:
Draw a grid with 16 squares on your sketch:
• X is the horizontal distance in number of pixels from the
top left corner 1. Draw a line from the centre of the top of the canvas to the
centre of the bottom to divide the sketch into half. After the
• Y is the vertical distance in number of pixels from the top point() statement add the statement:
left corner
line(200, 0, 200, 400);
The top left corner of the canvas has the coordinates (0,0).
2. Draw a line from the centre of the left side of the canvas to
strokeWeight() the centre of the right side to divide the sketch into four
By default, points, lines, and the borders around shapes are only squares. Add the statement:
one pixel in size. To make them bigger, use the strokeWeight() line(0, 200, 400, 200);
function to set the width of the stroke:
3. Draw lines dividing each of the quadrants into four squares
strokeWeight(width); so that you have a grid of 16 squares. Add the vertical lines
• width is the number of pixels to use by adding the statements:
line(100, 0, 100, 400);
Activity: Draw a Point Ten Pixels in Size
line(300, 0, 300, 400);
Set the size of the point to 10 pixels and draw it by:
Add the horizontal lines by adding the statements:
1. In setup(), after the print() statement, add the statement: line(0, 100, 400, 100);
strokeWeight(10); line(0, 300, 400, 300);

2. In draw(), after the background() statement, add the


statement:
point(200,200);

13 14
Drawing a Triangle Drawing a Rectangle
p5.js has a built-in function to draw a triangle: p5.js has a built-in function to draw a rectangle:
• triangle() • rect()
triangle() rect()
The triangle() function creates a shape by connecting three points The rect() function draws a rectangle:
with straight lines: rect(x, y, width, height);
triangle(x1, y1, x2, y2, x3, y3)
• x and y represent the coordinates of the upper-left corner of
• x1 and y1 represent the coordinates of the first point the rectangle
• x2 and y2 represent the coordinates of the second point • width is the width of the rectangle
• x3 and y3 represent the coordinates of the third point • height is the height of the rectangle
Activity: Draw your Triangle A rectangle with a height equal to its width is a square.
Draw the triangle from your paper drawing by: Activity: Draw Your Square
1. Using the grid we drew on the paper, estimate the Draw the square from your paper drawing:
coordinates of the 3 corners of the triangle. 1. Using the grid we drew on the paper, estimate the
Use the same coordinate values for the grid on the paper as we coordinates of the upper-left corner
used for the grid we just drew on our p5.js canvas: (0, 0) for 2. Using the grid we drew on the paper, estimate the width of
top left corner, (400, 400) for the bottom right. the square. Use that value for the height as well.
2. After the last line() statement, add the statement: 3. After the triangle() statement, add the statement:
triangle(0, 0, 0, 200, 200, 200);
rect(200, 0, 200, 200);
Use the coordinate values from your drawing for the triangle() Use the coordinate values from your drawing for the rect()
statement. statement.
Use the width for both the width and height parameters.
Bonus activity: Use a different rectMode()
The way the parameters to rect() are interpreted may be changed
with the rectMode() function:
1. Explore the rectMode() function in the online reference
2. Draw your rectangle using CENTER mode.

15 16
Drawing an Ellipse Setting Colours
p5.js has a built-in function to draw an ellipse: p5.js has built-in functions to set the colours of lines and the inside
• ellipse() of shapes and to turn off drawing borders around or filling shapes:

ellipse() • stroke() and noStroke

The ellipse() function draws an ellipse: • fill() and noFill()


ellipse(x, y, width, [height]) stroke() and fill()
• x and y represent the coordinates of the centre of the ellipse The stroke() function sets the color used to draw lines and borders
around shapes. The fill() function sets the color used to fill shapes:
• width is the width of the ellipse
stroke(colour)
• height is the height of the ellipse. If no height is specified, fill(colour);
the value of width is used for both the width and height. • colour can be a CSS string
An ellipse with a height equal to its width is a circle. All shapes drawn after the stroke() and fill() statements will
Activity: Draw Your Circle use the specified colours.
Draw the circle from your paper drawing: noStroke() and noFill()
1. Using the grid we drew on the paper, estimate the values The noStroke() function disables drawing the outline around
for the X and Y coordinates of the centre of the circle. shapes. The noFill() function disables filling shapes with colours
2. Using the grid we drew on the paper, estimate the width of and makes them transparent.
the circle by: noFill();
noStroke();
1. Drawing a horizontal line through the centre of the
circle Activity: Colour Your Shapes

2. Subtracting the X coordinate of the left end of the line Colour your shapes by:
from the X coordinate of the right end. 1. Turn off the borders around the shapes. After the
3. After the rect() statement, add the statement: background() statement, add the statement:
ellipse(200, 300, 200); noStroke();

Use the coordinate and width values from your drawing for the 2. Before each of the triangle(), rect(), and ellipse()
ellipse() statement. statements, add the statement:
fill('red');
Replace 'red' with the string for the colour of the shape from
your drawing.

17 18
Introducing Variability into the Sketches Varying the Placement of Your Circle
p5.js has a built-in function to generate random numbers we can We can use the random() function to generate random numbers
use to vary the placement of shapes each time the program is run: that we can pass as the parameters to the ellipse() function to use
• random() as the X and Y coordinates of our circle. First, we're going to save
the values of the coordinates from our drawings in variables using:
random()
• let
The random() function returns a random floating-point number:
let
random([min],[max])
The let keyword is used to specify a name for our variable, so we
• if no argument is given, returns a random number from 0 can refer to it later, and to optionally assign a value to it:
up to (but not including) 1
let myVariable = 1;
• if one argument is given, returns a random number from 0
up to (but not including) the number We're going to declare our variables at the very top of the sketch,
outside of the setup(), draw(), or any other functions. This will let
• if two arguments are given, returns a random number from every other part of the sketch use them.
the first argument up to (but not including) the second
argument Where variables are declared determines which other parts of
our sketch will be able to use them.
Activity: Print Random Numbers to the Console
Activity: Randomize the Placement of Your Circle
Print random numbers to the console by:
Save the initial values of the X and Y coordinates in variables and
1. After the last print() statement, add the following then generate new values for them each time the sketch is run by:
statements:
1. Before the setup() statement, add the statements:
print(random());
print(random(10)); let circleX = 200;
print(random(90,100)); let circleY = 300;

1. Run the sketch. Random numbers are printed to the Use the X and Y coordinate values of your circle
Console pane 2. Change the ellipse() statement to be:
2. Run the sketch again. Different numbers are printed. ellipse(random(circleX),random(circleY), 200);
Bonus Activity: Convert the Numbers to Integers Bonus Activity: Make the Circle Follow Your Mouse
You can convert the floating-point numbers returned by random() p5.js has two built-in variables that always hold the current
into integers using the int() function: position of the mouse (mouseX and mouseY):
1. Explore the int() function in the online reference. Print 1. Use mouseX and mouseY as the parameters for X and Y
random integers to the Console pane. in the ellipse() statement to make the circle follow your
mouse pointer.

19 20
Controlling the Draw Loop Varying the Placement of Your Square
The setup() function runs once. After that, the draw() function We can use the random() function to generate random numbers
keeps running over and over until you press the Stop button. p5.js that we can pass as the parameters to rect() as the X and Y
provides built-in functions we can use to control the draw() loop: coordinates to the function that draws our square:
• noLoop() and loop() rect(x, y, width, height)

noLoop() and loop() Activity: Randomize the Placement of Your Square


The noLoop() function stops p5.js from continuously executing We can vary the placement of the square by saving our initial
the code within draw(). If the loop() function is called, the code in values in variables and then generating new values each time the
draw() begins to run continuously again. sketch is run using random():
Activity: Stop the Circle from Bouncing Around 1. After the last let statement at the top of the sketch add the
statements:
We can stop the circle from bouncing around using the noLoop()
function: let squareX = 200;
let squareY = 0;
1. As the last line of the setup() function, add the statement:
2. Change the rect() statement to be:
noLoop();
rect(random(squareX),random(squareY), 200, 200);
2. Click the Play button. Click the Play button again to run the
sketch again or click the Stop button to stop it.
Bonus activity: Click the Mouse to Make the Circle Move
The mouseClicked() function is called once after a mouse button
has been pressed and then released. By default, this function does
nothing. To be useful to us, we have to declare the function and
add the code we want to be executed:
The redraw() function executes the code within draw() one time.
This function allows the sketch to update the display window only
when necessary.
To redraw the sketch whenever the mouse is clicked on it:
1. At the very bottom of the sketch, after the draw() function,
add these statements:
function mouseClicked() {
redraw();
}

21 22
Placing Shapes Anywhere on the Canvas Varying the Placement and Shape of Your
Using the variables we defined for the X and Y coordinates of the Triangle
centre of the circle (circleX and circleY) and for the top left corner We can use the random() function to generate random numbers
of the square (squareX and squareY) as the parameters to that we can pass as the parameters for the X and Y coordinates to
random() means that the centre of our circle can only be between the function that draws our triangle:
the top left corner of the canvas (0, 0) and the point with triangle(x1, y1, x2, y2, x3, y3);
coordinates (circleX, circleY) and the top left corner of our square
can only be between (0, 0) and (squareX, squareY). Unlike the ellipse() and rect() functions, which take X and Y
coordinates for a single point to place the shape, the triangle
p5.js has built-in variables that contain values for the width and function takes three pairs of X and Y coordinates, one for each
height of the canvas: point of the triangle.
• width If we use random() for each of the six coordinates, the triangle
• height won't just be placed in a different location, it will be drawn with a
different size and shape.
width
Activity: Randomize the Coordinates of Your Triangle
width is set to the width of the drawing canvas in pixels. This
value is set by the first parameter to the createCanvas() function. Change the shape and placement of the triangle by:
height 1. After the last let statement at the top of the sketch add the
statements:
height is set to the height of the drawing canvas in pixels. This
value is set by the second parameter to the createCanvas() let triangleX1 = 0;
let triangleY1 = 0;
function. let triangleX2 = 0;
We don't have to declare built-in variables with let before we let triangleY2 = 200;
let triangleX3 = 200;
use them.
let triangleY3 = 200;
Activity: Replace the Parameters to random()
2. Change the triangle() statement to be:
We can use the built-in variables width and height to vary the triangle(random(triangleX1), random(triangleY1),
placement of the circle and square to be anywhere on the canvas random(triangleX2), random(triangleY2),
by: random(triangleX3), random(triangleY3));

1. Change the ellipse() statement to be:


ellipse(random(width), random(height), 200);
2. Change the rect() statement to be:
rect(random(width),random(height), 200, 200);

23 24
Preserving the Shape of Your Triangle Varying the Size of Your Circle
We can preserve the shape of the triangle by picking one corner We were able to vary the placement of shapes by generating
and then expressing the X and Y coordinates of the other two random numbers to use as the parameters for the X and Y
corners in relation to the X and Y coordinates of the first corner. coordinates. We can vary the size of the circle by using random()
Activity: A Little Bit of Math to generate a random number to use as the parameter for its width.

Express the X and Y coordinates of the second and third corners as Activity: Vary the Width of Your Circle
the difference from the X and Y coordinates of the first corner by: To vary the size of the circle, declare a variable for the width of the
1. At the top of the sketch, change the let statement for circle, assign the values from your drawing to use as the initial
triangleX2: value, and then use that initial value to generate a random number
to use as the new width:
let triangleX2 = 0 - triangleX1;
1. After the let statement for circleY, add the statement:
2. Change the let statement for triangleY2:
let circleWidth = 200;
let triangleY2 = 200 - triangleY1;
2. Change the ellipse() statement to be:
3. Change the let statement for triangleX3:
ellipse(random(width), random(height),
let triangleX3 = 200 - triangleX1; random(circleWidth));
4. Change the let statement for triangleY3: Activity: Let the Circle be as Wide as the Canvas
let triangleY3 = 200 - triangleY1;
Using the circleWidth variable we defined as the parameter to
5. Generate random numbers to use as the X and Y random() means that the circle can only be smaller than the
coordinates for the first corner. Before the triangle() original. We can use the built-in width variable as the parameter to
statement, add the lines: random() to allow the circle to be as wide as the canvas:
triangleX1 = random(width); 1. Change the ellipse() statement to be:
triangleY1 = random(height);
ellipse(random(width), random(height),
6. Draw the triangle expressing the X and Y coordinates of the random(width));
second and third corners as a distance from the X and Y Bonus Activity: Keep the Circle Smaller than the Canvas
coordinates of the first corner. Change the triangle()
statement to be: To keep the circle smaller than the canvas, it's width has to be
smaller than whichever of the width or height is smallest:
triangle(triangleX1, triangleY1, triangleX1 +
triangleX2, triangleY1 + triangleY2, triangleX1 1. Explore the if-else statement in the online reference. Use it
+ triangleX3, triangleY1 + triangleY3); to pass the smallest of width or height to random().

25 26
Varying the Size of Your Square Varying the Colour of Your Shapes
We can vary the size of the square by using random() to generate We're going to use a new variable type, an array, as a way to vary
random number to use as the parameter for its width and height. the colour of the shapes each time the sketch is played. We can
Activity: Vary the Size of Your Square change the order of the elements in an array using the built-in
function:
To vary the size of the square, declare variables for its width and
height, assign the values from your drawing to use as the initial • shuffle()
values, and then use those initial values to generate random Array
numbers to use as the width and height: An Array is a special variable type which can hold more than one
1. After the let statement for squareY, declare the new value at a time. Up to now our variables could only hold one value
variables and assign their initial values: at a time.
let squareWidth = 200; We could declare three variables and assign CSS strings as their
let squareHeight = 200;
value with these statements:
2. Change the rect() statement to be: let colour0 = "red";
rect(random(width), random(height), let colour1 = "yellow";
random(squareWidth), random(squareHeight)); let colour2 = "blue";

Activity: Preserve the Proportions of Your Square Instead of declaring three variables, we can declare an array
variable named arrayOfColours with this statement:
Unlike the ellipse() statement, which lets us omit the height
let arrayOfColours = [ 'red', 'yellow', 'blue' ];
parameter, the rect() statement needs parameters for both the width
and the height. Because we are using two different random • The left and right brackets indicate that this is an array
numbers for the width and height, the rect() statement (mostly) variable.
draws a rectangle, not a square. • Each element in the array is separated by a comma.
To preserve the proportions of the square, we have to generate and • Each element in the array is identified by an index number
store a random number and then use it as the value for both the starting with 0
width and the height parameters:
We can reference the value stored in a specific element of the array
1. Before the rect() statement, add the statements: by using the name of the array followed by the index number of
squareWidth = random(width); that element. To reference the value 'red', we would use:
squareHeight = squareWidth;
arrayOfColours[0]
2. Change the rect() statement to be:
Array index numbers start at 0.
rect(random(width), random(height),squareWidth,
squareHeight);

27 28
shuffle() Creating a Custom Shape
The shuffle() function randomizes the order of the elements of an We can create our own shapes using the built-in functions:
array passed to it as a parameter:
shuffle(array, boolean);
• beginShape()
• endShape()
• array is the name of the array variable
• vertex()
• boolean is one of true or false. true means to modify the
array passed as the parameter. false means to return a new beginShape() and endShape()
array. The beginShape() and endShape() functions allow the creation
We want to use true for this workbook. of more complex forms:
Activity: Shuffle the Colours of the Shapes beginShape();
// add any number of vertex() statements
Replace the CSS strings we've been using as parameters to the fill() endShape();
function with elements from an array holding the CSS strings by:
• beginShape() begins recording vertices for a shape
1. After the last let statement, add the statement:
• endShape() stops recording vertices
let arrayOfColours = [ 'red', 'yellow',
'blue' ]; vertex()
Use the CSS strings for the colours from your drawing as the The vertex() function specifies a point of your shape to be
values for the array elements. connected by a line:
vertex(x, y);
2. After the background() statement, add the statement:
shuffle(arrayOfColours, true); Activity: Add a Five-sided Shape to Your Sketch
3. Change the first fill() statement to be: You can create a shape with any number of vertex() statements.
fill(arrayOfColours[0]);
Add a five-sided shape and colour the shape using one of the three
available colours choosen at random by:
4. Change the second fill() statement to be:
1. After the ellipse() statement, add the statements:
fill(arrayOfColours[1]);
fill(arrayOfColours[int(random(0,3))]);
5. Change the third fill() statement to be: beginShape();
vertex(random(width), random(height));
fill(arrayOfColours[2]);
vertex(random(width), random(height));
Each fill() statement uses a different index number to reference vertex(random(width), random(height));
vertex(random(width), random(height));
different elements in the array variable arrayOfColours. vertex(random(width), random(height));
endShape();

29 30
Looping Through the Variations Preparing Your Sketch to Share
By default, p5.js loops continuously through the draw() function, Before we share our sketches, we can make the canvas as large as
executing the code within it. Earlier, we turned off looping with the the browser window and change the background colour to
noLoop() function. We can resume looping through variations of something more interesting than grey using:
our sketch and control the speed of the loop with the built-in • background()
functions:
• windowWidth
• loop()
• windowHeight
• frameRate()
background()
loop()
The background() function sets the colour used for the
The loop() function resumes looping through the draw function if background of the p5.js canvas. This function is typically used
it has been turned off by a call to the noLoop() function: within draw() to clear the display window at the beginning of each
loop(); frame.
frameRate() As we've seen, one of the easiest way to specify a colour for the
The frameRate() function specifies the number of frames (or background is by using a CSS string:
loops) to be displayed every second. A frame rate of 24 frames per background('white');
second (usual for movies) or above will be enough for smooth windowWidth and windowHeight
animations:
frameRate(24);
windowWidth and windowHeight are built-in variables that hold
the values in pixels of the browser window's width and height:
Activity: Loop Through One Sketch Each Second
Because windowWidth and windowHeight are built-in
Loop through one sketch each second by turning looping back on variables, we do not have to declare them with let before we
and specifying a frame rate of 1: use them
1. After the noLoop() statement, add the statements: Activity: Change the Colour and Size of the Background
loop();
Change the background colour to white or black and make it as
frameRate(1);
large as the browser window:
Bonus Activity: Frame Rates of Less than 1
1. Change the background() statement to be:
Frame rates of less than 1 can be specified using a floating-point background('black');
number between 0 and 1. Make your sketch loop through one
sketch every 10 seconds. 2. Change the createCanvas() statement to be:
createCanvas(windowWidth, windowHeight);

31 32
Sharing Your Sketch What's Next?
We can share our sketches directly from the p5.js web editor Try these resources to learn more about what p5.js can do and how
website or by downloading the sketch and hosting it on our you can use it.
computer or web server. Resources on the p5.js Web Site
Sharing from the Website These are just a few of the links at https://p5js.org/learn/:
Sketches can be shared from the website in a number of ways: • p5.js Overview: An overview of the main features of p5.js.
• Embed • Coordinate System and Shapes: Drawing simple shapes and
• Present using the coordinate system.
• Fullscreen
• Edit • Interactivity: Introduction to interactivity with the mouse
and keyboard.
To share a sketch, go to the File menu and select Share.
• Program Flow: Introduction to controlling program flow in
Downloading to a Computer p5.js.
You can download a .zip file of the files that make up a sketch and • Color: An introduction to digital color.
host them from your own computer or web server. The .zip file will
contain these files: • Beyond the canvas: Creating and manipulating elements on
the page beyond the canvas.
• index.html
• sketch.js • 3D/WebGL: Developing advanced graphics applications in
• style.css p5.js using WEBGL mode.
• p5.js Online Courses
• p5.sound.min.js
There are free courses offered by some of the online learning
To download a sketch, go to the File menu and select Download. websites:
Activity: Share Your Sketch • Creative Coding on edX
Go to the File menu and select Share. URLs for each of the sharing https://www.edx.org/course/creative-coding
methods will be displayed.
• Introduction to Programming for the Visual Arts with p5.js
1. Copy and paste the URLs for Present, Fullscreen, and Edit on Kadenze
into a browser window to see how they differ
https://www.kadenze.com/courses/introduction-to-
Bonus Activity: Download Your Sketch programming-for-the-visual-arts-with-p5-js-iii
To download your sketch, go to the File menu and select
Download. Download and unzip the file. Use your browser to find
and open the index.html file.

33 34
print(random(10)); // Introducing Variability into the
The Completed Sketch Sketches
print(random(90, 100)); // Introducing Variability into the
Here's a copy of the sketch created by completing the activities in Sketches
this workbook. Statements from every activity are included and strokeWeight(10); // Drawing a Point
commented out as they were changed. Comments at the end of
// noLoop(); // Controlling the Draw Loop
each line refer back to the section the activity came from. loop(); // Looping Through the Variations
frameRate(1); // Looping Through the Variations
}
let circleX = 200; // Varying the Placement of the Circle function draw() {
let circleY = 300; // Varying the Placement of the Circle // background(220); // Skeleton sketch
let circleWidth = 200; //Varying the Size of Your Circle // background('lightgrey'); // Changing the Colour of the
Canvas
let squareX = 200; // Varying the Placement of the Square background('black'); // Preparing our Sketches to Share
let squareY = 0; // Varying the Placement of the Square
let squareWidth = 200; // Varying the Size of Your Square shuffle(arrayOfColours, true); // Varying the Colour of the
let squareHeight = 200; // Varying the Size of Your Square Shapes
let triangleX1 = 0; // Varying the Placement and Shape of Your noStroke(); // Setting Colours
Triangle
let triangleY1 = 0; // Varying the Placement and Shape of Your point(200, 200); // Drawing a Point
Triangle
// let triangleX2 = 0; // Varying the Placement and Shape of line(200, 0, 200, 400); // Drawing a Line
Your Triangle line(0, 200, 400, 200); // Drawing a Line
// let triangleY2 = 200; // Varying the Placement and Shape of line(100, 0, 100, 400); // Drawing a Line
Your Triangle line(300, 0, 300, 400); // Drawing a Line
// let triangleX3 = 200; // Varying the Placement and Shape of line(0, 100, 400, 100); // Drawing a Line
Your Triangle line(0, 300, 400, 300); // Drawing a Line
// let triangleY3 = 200; // Varying the Placement and Shape of
Your Triangle // fill('red'); // Setting Colours
let triangleX2 = 0 - triangleX1; // Preserving the Shape of fill(arrayOfColours[0]); // Varying the Colour of the Shapes
Your Triangle
let triangleY2 = 200 - triangleY1; // Preserving the Shape of // triangle(0, 0, 0, 200, 200, 200); // Drawing a Triangle
Your Triangle // triangle(random(triangleX1), random(triangleY1),
let triangleX3 = 200 - triangleX1; // Preserving the Shape of random(triangleX2), random(triangleY2), random(triangleX3),
Your Triangle random(triangleY3)); // Varying the Placement and Shape of Your
let triangleY3 = 200 - triangleY1; // Preserving the Shape of Triangle
Your Triangle triangleX1 = random(width); // Preserving the Shape of Your
Triangle
let arrayOfColours = ['red', 'yellow', 'blue']; // Varying the triangleY1 = random(height); // Preserving the Shape of Your
Colour of the Shapes Triangle
triangle(triangleX1, triangleY1, triangleX1 + triangleX2,
triangleY1 + triangleY2, triangleX1 + triangleX3, triangleY1 +
function setup() { triangleY3); // Preserving the Shape of Your Triangle
// createCanvas(400, 400); // Skeleton sketch
// createCanvas(200,600); // Creating a Canvas // fill('yellow'); // Setting Colours
createCanvas(windowWidth, windowHeight); // Preparing our fill(arrayOfColours[1]); // Varying the Colour of the Shapes
Sketches to Share

print('What colour is your circle?'); // Printing a Message // rect(200, 0, 200, 200); // Drawing a Rectangle
to the Console Pane // rect(random(squareX),random(squareY), 200, 200); //
Varying the Placement of the Square
print(random()); // Introducing Variability into the Sketches

35 36
// rect(random(width), random(height), 200, 200); // Placing
Shapes Anywhere on the Canvas
// rect(random(width), random(height), random(squareWidth),
random(squareHeight)); // Varying the Size of Your Square
squareWidth = random(width); // Varying the Size of Your
Square
squareHeight = squareWidth; // Varying the Size of Your
Square
rect(random(width), random(height), squareWidth,
squareHeight); // Varying the Size of Your Square

// fill('blue'); // Setting Colours


fill(arrayOfColours[2]); // Varying the Colour of the Shapes

// ellipse(200, 300, 200); // Drawing and Ellipse


// ellipse(random(circleX),random(circleY), 200); // Varying
the Placement of the Circle
// ellipse(random(width), random(height), 200); //Placing
Shapes Anywhere on the Canvas
// ellipse(random(width), random(height),
random(circleWidth)); // Varying the Size of Your Circle
ellipse(random(width), random(height), random(width)); //
Varying the Size of Your Circle

fill(arrayOfColours[int(random(0, 3))]); // Creating a Custom


Shape
beginShape(); // Creating a Custom Shape
vertex(random(width), random(height)); // Creating a Custom
Shape
vertex(random(width), random(height)); // Creating a Custom
Shape
vertex(random(width), random(height)); // Creating a Custom
Shape
vertex(random(width), random(height)); // Creating a Custom
Shape
vertex(random(width), random(height)); // Creating a Custom
Shape
endShape(); // Creating a Custom Shape
}

37

You might also like