Lesson 1 of 5

🎨 Drawing with Code

Learn how to create shapes and colors using JavaScript and p5.js

👋 Welcome to Coding!

Programming is like giving instructions to a computer. The computer follows your instructions exactly, step by step. Today, you'll learn to draw by writing code!

We'll use a tool called p5.js that makes it easy to create visual art with code. Let's start!

📐 The Canvas

First, we need a place to draw. In p5.js, this is called a canvas. Think of it like a piece of paper.

🔑 Key Concept: Coordinates

Every point on the canvas has an x (horizontal) and y (vertical) position.

  • x = 0 is the left edge
  • y = 0 is the top edge (this might seem backwards!)
  • • Numbers get bigger as you go right (x) and down (y)

👆 See how the green dot is at the top-left corner? That's position (0, 0)!

🎨 Background Color

The background() function fills the entire canvas with a color.

🔑 Colors in Code

Colors use RGB values (Red, Green, Blue), each from 0 to 255:

  • background(0) = black
  • background(255) = white
  • background(255, 0, 0) = red
  • background(0, 255, 0) = green
  • background(0, 0, 255) = blue
  • background(135, 206, 235) = sky blue

✏️ Try it: Change the background

⭕ Drawing Shapes

Now let's draw some shapes! p5.js has functions for common shapes:

circle(x, y, diameter)

Draws a circle at position (x, y) with the given diameter.

circle(200, 200, 100);

rect(x, y, width, height)

Draws a rectangle. (x, y) is the top-left corner.

rect(100, 100, 200, 150);

line(x1, y1, x2, y2)

Draws a line from point (x1, y1) to point (x2, y2).

line(0, 0, 400, 400);

triangle(x1, y1, x2, y2, x3, y3)

Draws a triangle with three corner points.

triangle(200, 100, 100, 300, 300, 300);

✏️ Try it: Draw shapes

🌈 Coloring Shapes

Use fill() to set the inside color and stroke() for the outline color.

🔑 Important!

fill() and stroke() affect all shapes drawn after them. It's like picking up a colored pencil!

noFill() - Makes shapes transparent (outline only)

noStroke() - Removes the outline

strokeWeight(n) - Sets outline thickness

🏆 Challenge: Draw a House

Use what you've learned to draw a simple house! You'll need:

  • • A rectangle for the house body
  • • A triangle for the roof
  • • A small rectangle or square for the door
  • • Circles or squares for windows
  • • A nice background color (maybe sky blue?)

🎨 Final Project: Draw Your Scene

Now it's your turn to be creative! Draw any scene you want. Here are some ideas:

  • • 🌊 Underwater scene with fish
  • • 🚀 Outer space with planets and stars
  • • 🌲 A forest with trees
  • • 😊 A face or character
  • • 🏙️ A city skyline

📝 What You Learned

Concepts

  • ✅ Canvas coordinates (x, y)
  • ✅ RGB color values (0-255)
  • ✅ The setup() and draw() functions

Functions

  • ✅ background(), fill(), stroke()
  • ✅ circle(), rect(), line(), triangle()
  • ✅ noFill(), noStroke(), strokeWeight()