Introduction to JavaScript and Creative Coding
Welcome to "Introduction to JavaScript and Creative Coding", a journey into the world of programming and artistic expression. This article-book is designed to introduce you to JavaScript, one of the most popular programming languages in the world, and show you how to use it for creative coding through the p5.js library (integrated with modifications in codeguppy.com). Whether you are completely new to coding or have some experience, this book will guide you through the essentials of JavaScript while focusing on building interactive, dynamic, and visually engaging projects.
Creative coding is a blend of programming and creativity, where code is used as a tool for artistic expression. Throughout this book, you will learn how to write code to create visual art, animations, and interactive experiences. From understanding the basics of JavaScript syntax to building interactive games and generative art, you’ll gain practical coding skills while exploring your creative side.
Each chapter will introduce new concepts with hands-on examples and projects that let you apply what you've learned immediately. By the end of the book, you will not only be comfortable with JavaScript but also equipped to build your own creative coding projects and share them with the world.
Get ready to explore the exciting world of code-driven creativity!
Chapter 1: Getting Started with JavaScript
JavaScript is a powerful and versatile programming language that is widely used for web development, interactive applications, and creative coding projects. In this book, we’ll focus on using JavaScript alongside a set of graphical functions, which simplifies drawing and animation, allowing us to quickly dive into visual programming.
By the end of this chapter, you’ll have written your first JavaScript program. Let’s get started!
1.1 What is JavaScript?
JavaScript is a high-level, interpreted programming language that runs in web browsers. Initially created to add interactivity to web pages, it has grown into one of the most popular and widely used languages. JavaScript allows you to:
- Create interactive websites
- Build games and animations
- Work with multimedia (images, sound, video)
- Handle data from APIs (Application Programming Interfaces)
- And much more!
In this book, we will focus on the creative side of JavaScript, using it to generate visuals, interactive art, and animations.
1.2 Setting Up Your Coding Environment
The easiest way to start coding with JavaScript is to use the integrated coding editor from codeguppy.com. This editor is entirely web-based, so you don’t need to install anything on your computer. Follow these steps to get started:
- Go to the codeguppy.com website: Open your browser and navigate to https://codeguppy.com/.
- Create an account: You can sign up for a free account if you want to save your projects and revisit them later.
- Start a new project: Click on the "Code Now" button to open a blank canvas where you can begin writing JavaScript.
This editor allows you to write, run, and save your code directly in the browser, making it easy to experiment and test your creative ideas.
1.3 The Basics of JavaScript Syntax
Before jumping into drawing, let’s understand some of the fundamental rules and syntax of JavaScript.
- Case Sensitivity: JavaScript is case-sensitive, meaning
myVariable
andmyvariable
are treated as different variables. - Semicolons: JavaScript statements are typically followed by a semicolon (
;
), though modern JavaScript often lets you omit them. However, it’s good practice to include them. - Comments: Use comments to make notes in your code without affecting its execution. Comments can be single-line (
//
) or multi-line (/* ... */
).
Example:
// This is a single-line comment
/* This is a multi-line
comment */
1.4 Writing Your First Program
Now, let’s write our first program to draw a circle:
background(220); // Sets the background color to light gray
circle(400, 300, 300); // Draws a circle at (400, 300) with a diameter of 300
Here’s what’s happening:
background(220)
fills the canvas with a light gray color.circle(400, 300, 300)
draws a circle centered at(400, 300)
with a width and height of 300 pixels.
Click the play button in the code editor, and you should see a circle appear on your canvas.
1.5 Debugging programs using the println instruction
JavaScript programs typically run in the browser, and one of the most useful tools for debugging and experimenting is the browser's console. The console allows you to view messages, errors, and outputs from your JavaScript code.
You can send messages to the console using the console.log()
function, which is very useful for tracking the flow of your program or checking the value of variables.
However, in codeguppy.com, there is an easier way to quickly display messages to help you debug your program. You can use the println()
function.
Try adding this line to the above program:
println("Hello, world!");
When you run the program, you’ll see "Hello, world!" appear over the canvas, showing that your code is working correctly.
Summary
In this chapter, we introduced JavaScript and its role in creative coding, and wrote our first simple program. You also learned how to use println
for debugging and gained a basic understanding of JavaScript syntax.
Now that you have your environment ready and understand the basics, you're prepared to dive deeper into the world of coding and creativity! In the next chapter, we’ll explore variables, data types, and how to control the flow of your code.
Chapter 2: Variables, Data Types, and Operators
Now that you're familiar with the basics, it’s time to dive deeper into programming concepts like variables, data types, and operators. These concepts are the foundation of programming and allow us to build more complex and dynamic programs.
In this chapter, you’ll learn how to:
- Use variables to store and manipulate data
- Work with different data types
- Perform basic operations using operators
2.1 Variables and Constants
Variables are used to store information that can be referenced and manipulated in a program. You can think of variables as containers that hold data, which can change as the program runs.
Declaring Variables
In JavaScript, variables can be declared using the let
keyword (or const
for constants). Here’s how you declare a variable:
let x = 10; // Declares a variable named 'x' and assigns it a value of 10
- The keyword
let
indicates that the value ofx
can change later in the program. - The equal sign (
=
) is the assignment operator, which assigns the value on the right to the variable on the left.
Constants
Constants are variables whose value cannot change once they are set. You declare constants using the const
keyword:
const pi = 3.14159; // Declares a constant 'pi' and assigns it a value of 3.14159
- Use constants for values that should not change, like mathematical constants or configuration settings.
2.2 JavaScript Data Types
JavaScript supports various data types that can be stored in variables. The most common data types are:
1. Numbers
Numbers can be either integers or floating-point values (decimals). For example:
let age = 16; // Integer
let price = 19.99; // Floating-point number
2. Strings
Strings are sequences of characters enclosed in quotes. You can use either single quotes ('
) or double quotes ("
):
let name = 'Luca'; // String with single quotes
let greeting = "Hello, world!"; // String with double quotes
3. Booleans
Booleans represent logical values: true
or false
:
let isStudent = true; // Boolean value 'true'
let isAdult = false; // Boolean value 'false'
4. Arrays
Arrays are lists of values, stored in square brackets. Each value can be accessed using an index number, starting from 0
:
let colors = ['red', 'green', 'blue']; // Array of strings
let numbers = [1, 2, 3, 4, 5]; // Array of numbers
5. Objects
Objects are collections of key-value pairs, allowing you to group related data:
let person = {
name: 'Luca',
age: 16,
isStudent: true
};
In this example, person
is an object with three properties: name
, age
, and isStudent
.
2.3 Working with Numbers and Strings
Numbers and strings are the two most common data types you’ll work with in creative coding. Let’s look at how you can manipulate them.
Numbers: Basic Arithmetic
You can use standard arithmetic operators to perform operations with numbers:
let sum = 5 + 3; // Addition
let difference = 10 - 6; // Subtraction
let product = 4 * 2; // Multiplication
let quotient = 20 / 5; // Division
let remainder = 10 % 3; // Modulus (remainder of division)
Strings: Concatenation
You can combine (concatenate) strings using the +
operator:
let firstName = 'Luca';
let lastName = 'Veteanu';
let fullName = firstName + ' ' + lastName; // Concatenates firstName and lastName
println(fullName); // Output: 'Luca Veteanu'
Strings can also be manipulated using built-in methods like length
, toUpperCase()
, and toLowerCase()
:
let message = "Hello, world!";
println(message.length); // Outputs the length of the string: 13
println(message.toUpperCase()); // Outputs the string in uppercase: 'HELLO, WORLD!'
println(message.toLowerCase()); // Outputs the string in lowercase: 'hello, world!'
2.4 Arithmetic, Logical, and Comparison Operators
Arithmetic Operators
As seen earlier, arithmetic operators are used to perform mathematical calculations:
+
(addition)-
(subtraction)*
(multiplication)/
(division)%
(modulus)
Comparison Operators
Comparison operators are used to compare values and return a Boolean (true
or false
):
==
(equal to)!=
(not equal to)>
(greater than)<
(less than)>=
(greater than or equal to)<=
(less than or equal to)
Example:
let a = 5;
let b = 10;
println(a > b); // Output: false (5 is not greater than 10)
println(a < b); // Output: true (5 is less than 10)
Logical Operators
Logical operators are used to combine multiple conditions:
&&
(AND): Returnstrue
if both conditions are true||
(OR): Returnstrue
if either condition is true!
(NOT): Reverses the Boolean value (true
becomesfalse
and vice versa)
Example:
let isSunny = true;
let hasUmbrella = false;
println(isSunny && hasUmbrella); // Output: false (both conditions are not true)
println(isSunny || hasUmbrella); // Output: true (one condition is true)
println(!isSunny); // Output: false (reverses true to false)
2.5 Input and Output in JavaScript
In interactive programs, you often want to take input from users and provide output based on their actions. One way to get input into JavaScript is to use functions like prompt()
Getting Input from the User
The prompt()
function displays a dialog box that allows the user to input a value:
let userName = prompt("What is your name?");
println("Hello, " + userName + "!");
Outputting to the Console
You can use println()
to print messages or values, which is useful for debugging:
let age = 16;
println("You are " + age + " years old."); // Outputs: "You are 16 years old."
Summary
In this chapter, we explored the core concepts of variables, data types, and operators in JavaScript. You now understand how to declare variables, work with different types of data (numbers, strings, booleans, arrays, and objects), and use operators to perform calculations and make comparisons.
With these concepts, you’re ready to start building more complex programs! In the next chapter, we’ll dive into control flow, which allows you to make decisions in your code and create interactive experiences.
Chapter 3: Control Flow in JavaScript
Now that you're familiar with variables and data types, it's time to learn about control flow. Control flow is what makes a program dynamic and interactive by allowing it to make decisions and repeat actions based on certain conditions. In this chapter, we will cover how to use conditional statements and loops in JavaScript to control the flow of your code.
By the end of this chapter, you'll know how to:
- Make decisions in your code using conditional statements
- Repeat actions using loops
- Break out of loops when needed
3.1 Conditional Statements (if, else if, else)
Conditional statements allow your program to make decisions based on certain conditions. In JavaScript, the most common conditional statement is the if statement.
The if
Statement
The if
statement executes a block of code only if a specified condition evaluates to true
.
Example:
let age = 18;
if (age >= 18)
{
println("You are an adult.");
}
In this example, the code inside the if
block will only run if the value of age
is 18 or greater.
The else
Statement
The else
statement specifies a block of code to execute if the condition in the if
statement is false
.
Example:
let age = 16;
if (age >= 18)
{
println("You are an adult.");
}
else
{
println("You are a minor.");
}
In this case, since the condition (age >= 18
) is false, the code inside the else
block will be executed, outputting "You are a minor."
The else if
Statement
The else if
statement allows you to test multiple conditions. If the first condition is false
, it moves on to the next condition.
Example:
let score = 85;
if (score >= 90)
{
println("You got an A!");
}
else if (score >= 80)
{
println("You got a B!");
}
else
{
println("You need to improve.");
}
In this example, the program checks the conditions one by one until it finds one that is true
.
3.2 Loops: for, while, do-while
Loops are used to repeatedly run a block of code as long as a certain condition is met. JavaScript provides several types of loops: for, while, and do-while.
The for
Loop
The for
loop is ideal when you know in advance how many times you want to loop through a block of code.
Syntax:
for (initialization; condition; increment)
{
// Code to be repeated
}
Example:
for (let i = 0; i < 5; i++)
{
println(i);
}
This loop will print the numbers 0 through 4. The i++
increases the value of i
by 1 after each loop iteration.
The while
Loop
The while
loop runs a block of code as long as a specified condition is true
.
Example:
let i = 0;
while (i < 5)
{
println(i);
i++;
}
This loop behaves similarly to the for
loop, but the condition is checked at the start of each iteration.
The do-while
Loop
The do-while
loop is similar to the while
loop, but it ensures that the block of code runs at least once, even if the condition is false
.
Example:
let i = 0;
do
{
println(i);
i++;
}
while (i < 5);
Here, the loop runs once before checking the condition.
3.3 Breaking Out of Loops
Sometimes, you might want to exit a loop before the condition is met. You can use the break
statement to do this.
Example:
for (let i = 0; i < 10; i++)
{
if (i === 5)
break; // Exit the loop when i equals 5
println(i);
}
In this example, the loop will stop once i
equals 5, and only the numbers 0 through 4 will be printed.
The continue
Statement
The continue
statement skips the rest of the current loop iteration and moves on to the next one.
Example:
for (let i = 0; i < 10; i++)
{
if (i % 2 === 0)
continue; // Skip even numbers
println(i);
}
This loop will print only odd numbers.
3.4 Creating Interactive Programs with Control Flow
With control flow, you can make your programs more dynamic and interactive. Let’s create a simple number guessing game using what we've learned.
let target = Math.floor(Math.random() * 10) + 1;
let guess;
while (guess !== target)
{
guess = parseInt(prompt("Guess a number between 1 and 10:"));
if (guess === target)
{
println("You guessed correctly!");
}
else if (guess > target)
{
println("Too high! Try again.");
}
else
{
println("Too low! Try again.");
}
}
In this game, the program generates a random number between 1 and 10, and the player must guess the number. The loop continues until the correct number is guessed.
Summary
In this chapter, we explored how to use control flow in JavaScript. You learned how to:
- Make decisions with
if
,else if
, andelse
statements - Repeat actions with
for
,while
, anddo-while
loops - Use the
break
andcontinue
statements to control the flow of loops
Control flow is essential for creating interactive and responsive programs. In the next chapter, we’ll take a look at functions and scope, which will allow you to organize your code into reusable blocks.
Chapter 4: Functions and Scope
In JavaScript, functions are a fundamental part of writing reusable and organized code. Functions allow you to group code into blocks that can be reused whenever needed, which helps to reduce redundancy and improve readability. In this chapter, we’ll explore how to create and use functions, pass data into them, and understand the concept of scope.
By the end of this chapter, you’ll be able to:
- Define and call functions
- Use parameters and return values
- Understand the difference between local and global scope
- Work with anonymous and arrow functions
4.1 Defining and Calling Functions
A function is a block of code designed to perform a specific task. You can define a function once and call it multiple times, saving time and avoiding repetition.
Defining a Function
Here’s how to define a simple function in JavaScript:
function greet()
{
println("Hello, world!");
}
- The
function
keyword is used to declare a function. - The name of the function in this case is
greet
. - The code inside the curly braces
{}
is what the function does when called.
Calling a Function
To call a function and execute its code, you use the function name followed by parentheses:
greet(); // This will output: Hello, world!
Let's put these together:
function greet()
{
println("Hello, world!");
}
greet();
4.2 Function Parameters and Return Values
Functions can accept parameters, which allow you to pass data into the function. They can also return a value after performing their task.
Parameters
You can pass values, known as arguments, to a function using parameters:
function greet(name)
{
println("Hello, " + name + "!");
}
greet("Luca"); // Output: Hello, Luca!
greet("Marian"); // Output: Hello, Marian!
In this example, the greet
function takes a parameter called name
and uses it inside the function to customize the greeting message.
Return Values
Sometimes, you want a function to perform a calculation and give back a result. You can use the return
keyword to return a value from a function.
Example:
function add(a, b)
{
return a + b;
}
let sum = add(3, 4);
println(sum); // Output: 7
Here, the add
function takes two parameters a
and b
, adds them together, and returns the result. The result is then stored in the variable sum
.
4.3 Local and Global Scope
Scope refers to the accessibility of variables in different parts of your code. JavaScript has two main types of scope: local scope and global scope.
Global Scope
Variables declared outside of any function are in the global scope, meaning they can be accessed from anywhere in the code.
Example:
let globalVar = "I am global!";
function showGlobalVar()
{
println(globalVar);
}
showGlobalVar(); // Output: I am global!
Local Scope
Variables declared inside a function are in the local scope and can only be accessed within that function.
Example:
function showLocalVar()
{
let localVar = "I am local!";
println(localVar);
}
showLocalVar(); // Output: I am local!
// Trying to access localVar outside the function will result in an error
// println(localVar); // Error: localVar is not defined
In this example, localVar
is only accessible within the showLocalVar
function. Trying to access it outside the function will result in an error.
4.4 Anonymous Functions and Arrow Functions
Anonymous Functions
An anonymous function is a function without a name. These are often used as arguments to other functions or assigned to variables.
Example:
let greet = function() {
println("Hello, anonymous world!");
};
greet(); // Output: Hello, anonymous world!
Arrow Functions
Arrow functions are a shorter way to write functions, introduced in ES6. They are often used for concise and readable code.
Example:
let add = (a, b) => {
return a + b;
};
println(add(3, 4)); // Output: 7
If the function only has one statement, you can omit the curly braces and return
keyword:
let multiply = (a, b) => a * b;
println(multiply(3, 4)); // Output: 12
Arrow functions have some subtle differences compared to regular functions, but for now, we’ll focus on their syntax and usage.
Summary
In this chapter, we covered how to define and use functions in JavaScript. You learned about:
- Defining and calling functions
- Passing parameters to functions
- Using the
return
statement to return values - The differences between local and global scope
- Writing anonymous and arrow functions for more concise code
Functions are essential for writing organized and reusable code. In the next chapter, we’ll explore how to work with arrays and objects to store and manipulate collections of data.
Chapter 5: Arrays and Objects
As your programs grow in complexity, you'll often need to work with groups of data.
JavaScript provides arrays and objects to handle collections of data efficiently.
In this chapter, we’ll explore how to use arrays to store lists of values and objects
to represent more complex data structures.
By the end of this chapter, you’ll understand how to:
- Create and manipulate arrays
- Work with common array methods
- Create and use objects
- Understand the differences between arrays and objects
5.1 Understanding Arrays
An array is a data structure that allows you to store multiple values in a single
variable. Arrays can hold any type of data, including numbers, strings, and even
other arrays or objects.
Declaring Arrays
You can declare an array using square brackets []
and separate each value with
a comma.
Example:
let colors = ['red', 'green', 'blue'];
let numbers = [1, 2, 3, 4, 5];
You can also create an array using the Array
constructor:
let fruits = new Array('apple', 'banana', 'cherry');
Getting the Length of an Array
You can obtain at any time the length of an array (to find out how many elements are in the array) by using the .length
property
Example:
println(colors.length);
println(numbers.length);
Accessing Array Elements
Each element in an array has an index, starting from 0. You can access elements
using their index value.
Example:
println(colors[0]); // Output: 'red'
println(numbers[2]); // Output: 3
You can change the value of an element by assigning a new value to it:
colors[1] = 'yellow';
println(colors); // Output: ['red', 'yellow', 'blue']
5.2 Working with Array Methods
JavaScript provides many built-in methods to work with arrays. Let's explore some
of the most commonly used methods.
Adding Elements
push()
: Adds one or more elements to the end of an array.unshift()
: Adds one or more elements to the beginning of an array.
Example:
colors.push('purple'); // Adds 'purple' to the end
println(colors); // Output: ['red', 'yellow', 'blue', 'purple']
numbers.unshift(0); // Adds 0 to the beginning
println(numbers); // Output: [0, 1, 2, 3, 4, 5]
Removing Elements
pop()
: Removes the last element of an array.shift()
: Removes the first element of an array.
Example:
let lastColor = colors.pop();
println(lastColor); // Output: 'purple'
println(colors); // Output: ['red', 'yellow', 'blue']
let firstNumber = numbers.shift();
println(firstNumber); // Output: 0
println(numbers); // Output: [1, 2, 3, 4, 5]
Finding Elements
indexOf()
: Returns the index of the first occurrence of a value.includes()
: Checks if an array contains a specific value.
Example:
let index = colors.indexOf('blue');
println(index); // Output: 2
let hasRed = colors.includes('red');
println(hasRed); // Output: true
5.3 Introduction to Objects
While arrays store lists of values, objects store collections of key-value pairs.
Each value is associated with a key, making it easier to work with more complex
data structures.
Creating an Object
You can create an object using curly braces {}
and specifying key-value pairs.
Example:
let person = {
name: 'Luca',
age: 16,
isStudent: true
};
Accessing Object Properties
You can access an object's properties using dot notation or bracket notation.
Example:
println(person.name); // Output: 'Luca'
println(person['age']); // Output: 16
You can also update properties in the same way:
person.age = 17;
println(person.age); // Output: 17
Adding and Deleting Properties
You can add new properties to an object or delete existing ones.
Example:
person.grade = '11th'; // Adds a new property
println(person.grade); // Output: '11th'
delete person.isStudent; // Deletes the 'isStudent' property
println(person); // Output: { name: 'Luca', age: 17, grade: '11th' }
5.4 Creating Objects from Blueprints Using Classes
Objects can be created from blueprints known as classes. Classes allow you to define a template for creating multiple objects with similar properties and methods. This is particularly useful when you need to create many objects that share the same structure but may have different values for their properties.
Defining a Class
In JavaScript, you can define a class using the class
keyword. Inside the class, you define a constructor, which is a special function that is called when you create a new object from the class. The constructor allows you to set the initial values of the object’s properties.
Example:
class Car
{
constructor(make, model, year)
{
this.make = make;
this.model = model;
this.year = year;
}
displayInfo()
{
println(\`\${this.year} \${this.make} \${this.model}\`);
}
}
In this example:
- We define a
Car
class with three properties:make
,model
, andyear
. - The
constructor
function initializes these properties whenever a new car object is created. - The
displayInfo()
method outputs the car's information.
Creating Objects from a Class
Once you’ve defined a class, you can create new objects from it using the new
keyword.
Example:
let car1 = new Car('Toyota', 'Camry', 2022);
let car2 = new Car('Honda', 'Civic', 2020);
car1.displayInfo(); // Output: 2022 Toyota Camry
car2.displayInfo(); // Output: 2020 Honda Civic
In this example:
- We create two
Car
objects:car1
andcar2
. - Each car object has its own set of properties, initialized with different values.
- We use the
displayInfo()
method to print out the details of each car.
Why Use Classes?
Classes provide a clean and reusable way to create objects with similar properties and methods. Instead of manually defining each object, you can define a class once and create multiple instances from it. This approach makes your code more organized, maintainable, and scalable, especially when dealing with complex applications.
5.5 Arrays vs. Objects: When to Use Which
- Use arrays when you need an ordered collection of values that can be accessed
by index. - Use objects when you need to represent entities with named properties.
For example:
- An array of numbers:
[10, 20, 30]
- An object representing a car:
{ make: 'Toyota', model: 'Camry', year: 2022 }
Summary
With arrays and objects, you now have the tools to store and manage data
effectively in your JavaScript programs.
In the next chapter, we’ll explore how to create animations and interaction , using what we’ve learned to make dynamic and interactive programs.
Chapter 6: Drawing with Code: Introducing p5.js
Now that you are familiar with JavaScript’s core concepts, it’s time to start exploring drawings, animations, and interactive art right in your browser.
In this chapter, we’ll cover:
- What p5.js is and how it works
- Setting up the p5.js environment
- Drawing basic shapes
- Working with color in p5.js
- Using variables to create dynamic drawings
6.1 What is Creative Coding?
Creative coding is a type of programming where the focus is on creating something expressive and artistic rather than solving traditional computational problems. With codeguppy.com and p5.js, you can create interactive visuals, generative art, games, and more, combining creativity with coding.
codeguppy.com simplifies the process of drawing shapes, handling interactions, and generating animations, making it a great tool for artists, designers, and beginners in programming.
6.2 Overview of p5.js Library
p5.js is based on Processing, a popular language for creative coding. It simplifies drawing and animation by providing functions that make it easy to manipulate the canvas, shapes, colors, and interactions.
Here are some key concepts:
- Canvas: This is the drawing area, similar to a blank sheet of paper, where you can draw shapes, lines, and text.
- Coordinates: p5.js uses a coordinate system where
(0, 0)
is the top-left corner of the canvas. Thex
value increases as you move to the right, and they
value increases as you move down.
codeguppy.com integrates a simplified version of the p5.js library, allowing you to explore the graphical functions without any complicated setup. You can read about the differences between plain p5.js and codeguppy.com in the other articles on this blog.
6.3 Drawing Shapes and Colors on Canvas
Drawing Basic Shapes
codeguppy.com (via p5.js) provides built-in functions to draw various shapes, such as rectangles, circles, and lines.
-
Circle: Draws a circle.
circle(400, 300, 300); // Draws a circle at (400, 300) with radius of 300
-
Ellipse (Circle/Oval): Draws a circle or oval.
ellipse(200, 200, 100, 100); // Draws a circle at (200, 200) with a width and height of 100
-
Rectangle: Draws a rectangle.
rect(50, 50, 100, 150); // Draws a rectangle at (50, 50) with a width of 100 and height of 150
-
Line: Draws a straight line between two points.
line(0, 0, 800, 600); // Draws a line from the top-left corner to the bottom-right corner
6.4 Working with Coordinates and Pixels
Everything you draw on the canvas is positioned using the coordinate system. The point (0, 0)
is at the top-left corner, and the coordinates increase as you move right and down. The canvas used by codeguppy.com has the size 800
by 600
pixels.
Example:
function loop()
{
clear();
circle(mouseX, mouseY, 50); // Draws a circle at the mouse pointer's position
}
In this example, mouseX
and mouseY
are built-in variables that store the current position of the mouse pointer. The circle follows the mouse as it moves around the canvas.
6.5 Dynamic Drawing: Variables in Art
You can use variables to create dynamic and interactive programs. By changing the values of variables over time, you can make shapes move, grow, and respond to user input.
Example:
let x = 0;
function loop()
{
clear();
circle(x, 300, 50); // Draws a circle at position (x, 300)
x = x + 2; // Moves the circle to the right
if (x > width)
{
x = 0; // Resets the circle to the left side of the canvas when it moves off-screen
}
}
In this example, the circle moves from left to right across the screen. When it reaches the edge of the canvas, it resets to the left side, creating a looping animation.
Summary
You now have the tools to start exploring creative coding. Whether you're drawing simple shapes or creating interactive artworks, the possibilities are endless.
Chapter 7: Animation and Interaction
codeguppy.com makes it easy to create animations and interactive experiences with just a few lines of code. In this chapter, you’ll learn how to make your program come to life by using the built-in animation loop and responding to user input.
By the end of this chapter, you’ll understand how to:
- Create simple animations
- Use the loop function
- Handle mouse and keyboard interaction
- Build interactive programs that respond to user input
7.1 Creating Simple Animations
In codeguppy.com, animations are created by continuously updating the position, size, or color of objects in the loop()
function. The loop()
function runs in a loop, which means the screen is updated many times per second.
Example:
let x = 0;
function loop()
{
clear();
circle(x, 300, 50);
x = x + 2; // Move the circle to the right
}
In this example, the circle's x
position is incremented by 2 on each frame, making it appear to move from left to right. As the loop()
function runs 60 times per second (by default), the animation appears smooth.
Frame Rate
The default frame rate is 60 frames per second (fps), but you can change this using the frameRate()
function.
Example:
frameRate(30); // Set the frame rate to 30 frames per second
Lowering the frame rate can create a slower, more deliberate animation, while raising it can create a faster, more dynamic experience.
7.2 Understanding the loop function
The loop()
function is called repeatedly to create animations. It works like a flipbook, where each frame is drawn one after another, creating the illusion of movement.
Clearing the Background
One key thing to remember when creating animations is that you need to clear the background on each frame to avoid leaving traces of previous frames. Without clearing the background, the shapes will "smear" across the canvas.
Example:
let x = 0;
function loop()
{
clear(); // Clear the background each frame
circle(x, 300, 50);
x = x + 2;
}
In this example, clear()
is called at the start of each frame to clear the screen, allowing the circle to move without leaving a trail. Exercise: Try commenting the clear()
line.
7.3 Mouse and Keyboard Interaction
p5.js makes it easy to create interactive programs that respond to user input. You can use built-in variables like mouseX
and mouseY
to track the mouse’s position, and functions like keyPressed()
to detect keyboard input. codeguppy.com inherit unchanged these concepts from p5.js.
Mouse Interaction
You can use the mouseX
and mouseY
variables to get the current position of the mouse. This allows you to create programs that respond to mouse movements.
Example:
function loop()
{
clear();
circle(mouseX, mouseY, 50); // Draw the circle at the mouse's position
}
In this example, the circle follows the mouse pointer as it moves across the screen.
Keyboard Interaction
You can detect key presses by using the keyPressed()
function or by checking the key
variable inside the draw()
function.
Example:
function loop() {
clear();
textSize(32);
if (keyIsPressed)
{
text(key, 200, 200); // Display the key being pressed
}
}
In this example, when a key is pressed, the key
variable stores the value of the key, which is then displayed on the canvas.
7.4 Responding to User Input in Visuals
p5.js allows you to create interactive experiences where the visuals respond to the user’s input. Let’s combine mouse and keyboard interactions to create a more dynamic sketch.
Example:
let size = 50;
function loop()
{
clear();
circle(mouseX, mouseY, size); // Draw a circle that follows the mouse
}
function keyPressed()
{
if (key === 'A' || key === 'a')
{
size += 10; // Increase the circle's size when 'A' is pressed
}
else if (key === 'S' || key === 's')
{
size -= 10; // Decrease the circle's size when 'S' is pressed
}
}
In this example, the circle follows the mouse, and its size changes when the user presses the 'A' (increase size) or 'S' (decrease size) keys. This sketch demonstrates how you can combine mouse and keyboard input to create interactive experiences.
7.5 Creative Examples: Interactive Sketches
Now that you know how to handle user input and create animations, you can combine these concepts to build interactive programs. Here are a few ideas for projects:
- Drawing App: Create a program where the user can draw on the canvas using the mouse.
- Interactive Game: Build a simple game where the user controls a character with the keyboard.
- Generative Art: Design an art project where shapes and colors change based on user input.
Example:
let brushSize = 10;
function loop()
{
if (mouseIsPressed)
{
circle(mouseX, mouseY, brushSize); // Draw circles where the mouse is pressed
}
}
function keyPressed()
{
if (key === 'C' || key === 'c')
{
clear(); // Clear the canvas when 'C' is pressed
}
else if (key === 'B' || key === 'b')
{
brushSize += 5; // Increase the brush size when 'B' is pressed
}
else if (key === 'S' || key === 's')
{
brushSize -= 5; // Decrease the brush size when 'S' is pressed
}
}
This simple drawing app lets the user draw circles by clicking and dragging the mouse. They can clear the canvas with the 'C' key and adjust the brush size using the 'B' and 'S' keys.
Summary
Animation and interaction are key to making your creative coding projects dynamic and engaging. As you experiment with these concepts, you’ll discover endless possibilities for creating fun and interactive experiences. In the next chapter, we’ll explore randomness and how to use it to create unpredictable and exciting visual effects.
Chapter 8: Working with Randomness
Randomness is a powerful tool in creative coding that can make your sketches feel more dynamic and unpredictable. By incorporating random values, you can introduce variability in shapes, colors, movement, and more. In this chapter, you’ll learn how to work with randomness in p5.js to create unpredictable and exciting visual effects.
By the end of this chapter, you’ll be able to:
- Generate random numbers in p5.js
- Use randomness to create unpredictable visuals
- Apply randomness in movement and shapes
- Control randomness to create structured chaos
8.1 Generating Random Numbers
In p5.js, the random()
function is used to generate random numbers. This function allows you to add variability to your sketches, such as random positions, sizes, and colors.
The random()
Function
The random()
function generates a floating-point number between two values.
Example:
let r = random(50, 100);
circle(200, 200, r); // Draws a circle with a random radius between 50 and 100
In this example, random(50, 100)
returns a random number between 50 and 100, which is then used as the width and height of the circle.
Random Integers
If you need an integer instead of a floating-point number, you can use the floor()
function to round down the random number.
Example:
let r = floor(random(1, 10));
textSize(32);
text(r, 200, 200); // Displays a random integer between 1 and 9
8.2 Creating Unpredictable Visuals
By introducing random values into different aspects of your sketch, you can create unique and unexpected visuals every time the sketch is run.
Example:
for (let i = 0; i < 10; i++)
{
let x = random(width); // Random x position
let y = random(height); // Random y position
let size = random(20, 80); // Random size
circle(x, y, size); // Draw a random circle
}
In this example, 10 circles are drawn at random positions with random sizes. Each time you run the sketch, the circles will be different.
8.3 Randomness in Movement and Shapes
Randomness is often used to create unpredictable movement or dynamic shapes in animations. Let’s look at how to make objects move randomly across the canvas.
Example:
let x, y;
x = width / 2;
y = height / 2;
function loop() {
clear();
let stepX = random(-5, 5); // Random horizontal movement
let stepY = random(-5, 5); // Random vertical movement
x = x + stepX;
y = y + stepY;
circle(x, y, 50); // Draw the moving circle
}
In this example, the circle moves randomly across the screen, with each frame updating its position based on a random step value. This creates a wandering movement that changes unpredictably.
8.4 Controlled Randomness for Art Projects
Sometimes, you want randomness to be less chaotic and more controlled. By constraining the range of random values, you can create structured variations that maintain some consistency while still feeling dynamic.
Example:
for (let i = 0; i < 10; i++)
{
let x = random(100, 300); // Random x within a narrower range
let y = random(100, 300); // Random y within a narrower range
let size = random(50, 60); // Smaller random variation in size
rect(x, y, size, size); // Draw random squares
}
In this sketch, random squares are drawn, but the range of their positions and sizes is constrained, resulting in a more ordered but still varied design.
Summary
Randomness can add an exciting element of unpredictability to your creative coding projects, giving your sketches life and variability. By experimenting with random values, you can create unique outputs every time your code runs. In the next chapter, we’ll look at transforming shapes and visuals, including rotation, scaling, and translation, to further enhance your creative coding projects.
Chapter 9: Bringing It All Together: Creative Coding Projects
Now that you’ve learned the basics of JavaScript, p5.js, and various creative coding techniques, it’s time to put everything together and create some full projects. In this chapter, we’ll explore how to combine animation, interaction, randomness, and other skills to build complete creative coding projects. This chapter will guide you through the process of creating dynamic art installations, interactive games, and generative art projects, and show you how to present and showcase your work.
By the end of this chapter, you’ll be able to:
- Build larger, more complex projects
- Create interactive experiences using multiple techniques
- Understand how to showcase your creative work
9.1 Building a Dynamic Art Installation
A dynamic art installation often involves continuous animation, randomness, and interaction with the user. This project will combine these elements to create an engaging experience where the artwork evolves and responds to the user’s input.
Example: Interactive Particle System
let particles = [];
background(0);
function loop() {
clear();
// Add new particles
let p = new Particle(mouseX, mouseY);
particles.push(p);
// Update and display all particles
for (let i = particles.length - 1; i >= 0; i--)
{
particles[i].update();
particles[i].display();
// Remove particles that have faded out
if (particles[i].isFinished())
{
particles.splice(i, 1);
}
}
}
class Particle
{
constructor(x, y)
{
this.x = x;
this.y = y;
this.vx = random(-1, 1);
this.vy = random(-1, 1);
this.alpha = 255;
}
update()
{
this.x += this.vx;
this.y += this.vy;
this.alpha -= 5;
}
display()
{
noStroke();
fill(255, this.alpha);
ellipse(this.x, this.y, 20);
}
isFinished()
{
return this.alpha < 0;
}
}
In this project:
- A particle system generates particles that move randomly and fade out.
- New particles are generated at the mouse’s position.
- The
draw()
function continuously updates the particle system, resulting in a dynamic, evolving piece of art.
9.2 Interactive Games with JavaScript and p5.js
You can also combine your skills to create interactive games. In this section, we’ll create a simple game where the player controls an object on the screen and interacts with other elements in the environment.
Example: Simple Dodge Game
class Player
{
constructor()
{
this.x = width / 2;
this.y = height - 30;
this.size = 20;
}
update()
{
if (keyIsDown(LEFT_ARROW))
{
this.x -= 5;
}
else if (keyIsDown(RIGHT_ARROW))
{
this.x += 5;
}
this.x = constrain(this.x, 0, width);
}
display()
{
fill(0, 0, 255);
rect(this.x, this.y, this.size, this.size);
}
}
class Obstacle
{
constructor()
{
this.x = random(width);
this.y = 0;
this.size = 20;
this.speed = random(2, 5);
}
update()
{
this.y += this.speed;
// Reset the obstacle if it goes off the screen
if (this.y > height)
{
this.y = 0;
this.x = random(width);
}
}
display()
{
fill(255, 0, 0);
rect(this.x, this.y, this.size, this.size);
}
collidesWith(player)
{
return dist(this.x, this.y, player.x, player.y) < this.size;
}
}
let player;
let obstacles = [];
player = new Player();
// Create some obstacles
for (let i = 0; i < 5; i++)
{
obstacles.push(new Obstacle());
}
function loop()
{
clear();
// Update and display the player
player.update();
player.display();
// Update and display all obstacles
for (let i = 0; i < obstacles.length; i++)
{
obstacles[i].update();
obstacles[i].display();
// Check for collisions with the player
if (obstacles[i].collidesWith(player))
{
println("Hit!");
}
}
}
In this game:
- The player controls a square using the left and right arrow keys.
- Obstacles fall from the top of the screen, and the player must avoid them.
- The game stops when the player collides with an obstacle.
9.3 Generative Art: Combining Code and Creativity
Generative art is the creation of art using algorithms and random processes. You can use randomness, loops, and transformations to generate beautiful patterns and visuals that are different every time they are rendered.
Example: Randomized Geometric Patterns
for (let i = 0; i < 10; i++)
{
let x = random(width);
let y = random(height);
let size = random(20, 100);
let red = random(255);
let green = random(255);
let blue = random(255);
fill(red, green, blue, 150);
ellipse(x, y, size, size);
}
In this sketch:
- Random circles are drawn across the canvas with varying colors, sizes, and positions.
- Each time you run the code, a new pattern is generated, creating endless variations of the artwork.
9.4 Showcasing Your Creative Projects
Once you’ve created a project you’re proud of, you’ll want to share it with others. Here are some ways to showcase your work:
- Use the Share button: The codeguppy.com editor allows you to create, save, and share your programs online. You can send a link to anyone so they can interact with your project.
- Create a Portfolio: Build a simple website using HTML and JavaScript to showcase your creative coding projects. You can embed codeguppy.com programs directly into your website so that visitors can see your work live.
- Share on Social Media: Platforms like Twitter, Instagram, and Facebook do not usually allow you to share code and interactive programs. You can create however videos or GIFs of your generative art and share them with a larger audience.
Summary
Creative coding is all about experimentation and discovery. With the knowledge you’ve gained in this book, you’re well-equipped to explore new ideas and build unique projects that express your creativity.
Chapter 10: Next Steps in JavaScript and Creative Coding
Congratulations on making it to the final chapter! By now, you’ve learned the fundamentals of JavaScript and creative coding with with codeguppy.com, built interactive projects, and experimented with various techniques.
In this chapter, you’ll learn how to use p5.js to build sketches outside codeguppy.com, including setting up your development environment and creating your first sketch.
One of the great things about p5.js is that you can either install it locally on your machine or use it directly in an online playground (not codeguppy.com), making it flexible and accessible for everyone. Let's explore both options in this chapter.
10.1 Setting Up p5.js Locally
If you prefer to work locally on your computer, you can easily set up p5.js by downloading the necessary files and using a text editor to write your code.
Step-by-Step Setup:
-
Download p5.js: Head to the official p5.js website at https://p5js.org and download the latest version of the p5.js library. You can find the download link on the main page or under the "Download" section.
-
Create Your Project Folder: Once you've downloaded the p5.js files, create a new folder on your computer where you’ll store your sketches. For example, create a folder called
p5_sketches
. -
Add p5.js to Your Project: Move the
p5.js
library files into your project folder. -
Create Your HTML and JavaScript Files:
- Create an
index.html
file in your project folder. This HTML file will link to the p5.js library and serve as the foundation for running your sketches. - Create a
sketch.js
file where you will write your p5.js code.
- Create an
Sample index.html
File:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>p5.js Sketch</title>
<script src="p5.js"></script> <!-- Link to the p5.js library -->
<script src="sketch.js"></script> <!-- Link to your JavaScript file -->
</head>
<body>
</body>
</html>
Sample sketch.js
File:
function setup()
{
createCanvas(400, 400); // Create a 400x400 pixel canvas
}
function draw()
{
background(220); // Set the background color to gray
ellipse(200, 200, 100, 100); // Draw a circle in the middle of the canvas
}
- Open Your Project in a Browser: Once you have your
index.html
andsketch.js
files set up, open theindex.html
file in your browser to see your p5.js sketch in action.
Benefits of Local Setup:
- You have full control over the project files and folder structure.
- It’s easier to integrate with other tools and libraries.
- You can work offline.
10.2 Using the p5.js Web Editor
If you prefer not to install anything locally or want to quickly prototype sketches, p5.js offers an online web editor that allows you to code and run sketches directly in your browser.
Getting Started with the p5.js Web Editor:
-
Visit the p5.js Web Editor: Go to https://editor.p5js.org. The web editor is a complete development environment that runs directly in your browser, so you don’t need to install anything on your computer.
-
Create a New Sketch: Once you're on the site, you can create a new sketch by clicking the “New” button. The editor will automatically generate the basic structure of a p5.js project, including the
setup()
anddraw()
functions. -
Write Your Code: In the editor, write your p5.js code just like you would in a local setup. For example:
function setup()
{
createCanvas(400, 400); // Create a 400x400 pixel canvas
}
function draw()
{
background(255); // Set the background color to white
ellipse(mouseX, mouseY, 50, 50); // Draw a circle that follows the mouse
}
-
Run the Sketch: Click the “Play” button to run your sketch. The canvas will appear below the editor, and you’ll see your sketch in action.
-
Save and Share: You can create an account to save your sketches online and share them with others. The web editor generates a unique link for each sketch, allowing you to share your project by simply sending the link.
Benefits of the p5.js Web Editor:
- No installation required—just open your browser and start coding.
- Share your sketches instantly with a URL.
- Ideal for quick prototyping or when you're away from your local development environment.
- Collaborate easily with others by sharing links to your projects.
10.3 Core Functions in p5.js
Whether you are using p5.js locally or in the web editor, you'll primarily work with two core functions: setup()
and draw()
.
setup()
Function:
The setup()
function is called once when the program starts. It’s used to define the initial environment properties such as screen size, background color, and other settings. In codeguppy.com you don't need this function since codeguppy sets the environment to predefined parameters.
Example:
function setup()
{
createCanvas(600, 400); // Set the canvas size
background(100); // Set the background color to a dark gray
}
draw()
Function:
The draw()
function runs continuously and allows you to create animations or update visuals. Everything inside draw()
is executed repeatedly, so this is where you’ll update your sketch over time. This is similar to the loop()
function from codeguppy.com. As a matte of fact, the loop()
function is calling internally draw()
Example:
function draw()
{
background(255); // Clear the screen on every frame
ellipse(mouseX, mouseY, 50, 50); // Draw an ellipse that follows the mouse
}
In the example above, a white background is drawn continuously, and an ellipse follows the mouse pointer as it moves across the screen.
Summary
Your journey in creative coding and JavaScript doesn’t end here. There’s always more to learn, explore, and create. By continuing to build projects, experiment with new tools, and share your work, you’ll keep growing as a developer and creative coder.
Read more blog articles Browse JavaScript projectsAbout codeguppy
CodeGuppy is a FREE coding platform for schools and independent learners. If you don't have yet an account with codeguppy.com, you can start by visiting the registration page and sign-up for a free account. Registered users can access tons of fun projects!
Follow @codeguppy on Twitter for coding tips and news about codeguppy platform. For more information, please feel free to contact us.