言語設定

Basics of Drawing

Introduction

Today we are going to be learning how to write computer code using a tool called p5. Code is a set of instructions for the computer, telling it something to do. In our case, we will tell it to make a scene with shapes and colors.

First Sketch

When you open p5, your first sketch will look like this. There are two parts: setup and draw. Inside the curly brackets after setup and draw we will add code to create a drawing.

background(red, green, blue)

background() sets the background color of your drawing. You give it three numbers that represent the amount of red, green, and blue you want mixed into the background. The numbers range from 0-255. Try changing the numbers inside the parentheses to see what happens.

createCanvas(width, height)

createCanvas() sets the size of the drawing canvas. By default it is 100x100. You give it two numbers that represent the width and the height that you want your canvas to be. Try making your canvas different sizes by changing the width and height.

line(x1, y1, x2, y2)

line() draws a line on your canvas. You give it four numbers – the x and y position of one end, and the x and y position of the other end.

rect(x, y, width, height)

rect() draws a rectangle on your canvas. You give it four numbers – the x position, the y position, the width, and the height. For a rectangle, you give it the x,y position of the top left corner.

ellipse(x, y, width, height)

To draw a shape, think of your canvas like a piece of graph paper. However, square (0, 0) is in the top left.
ellipse() draws an ellipse on your canvas. You give it four numbers – the x position, the y position, the width, and the height.

fill(red, green, blue)

You can set the color of your shapes by using fill(). You give it three numbers – the red, green, and blue mixture you want, just like background.

stroke(red, green, blue)

You can set the outline color of your shapes by using stroke(). You give it three numbers – the red, green, and blue mixture you want, just like fill() and background().

strokeWeight(weight)

You can set the thickness of the outline for your shapes by using strokeWeight(). The default stroke weight is 1.

mouseX, mouseY

mouseX and mouseY can be used to get the current position of your mouse. They are called variables. You can replace a number in your code with mouseX or mouseY and that number will change as you move your mouse.

random(max)

random() will choose a random number for you, anywhere from 0 - max.

Links

Reference – available p5.js variables and functions
Examples – more complicated code examples