Drawing Basics
Goal:
This exercise will introduce the basics of how to create drawings using p5.js. In particular it will introduce:
- The p5.js cooridinate system
- The ellipse(), triangle() and rect() functions for drawing circles, triangles and rectangles
- colours
- stroke() and fill()
Try it Here:
https://thimble.mozilla.org/projects/39863/remix
Basics:
Coordinate System and Canvas:
In p5.js the top left corner of the drawing surface has a coordiante of 0,0. The bottom right corner is width-1, height-1. where width and height are values set by the createCanvas(); function call in setup.
Thus, createCanvas(x,y) will create a drawing surface for your sketch x pixels wide, y pixels tall. Each pixel has a coordinate. When you draw, you will use these coordinates to place objects. Depending on what you are drawing and the drawing mode, the coordinate can represent the location of the centre of the shape or one of its corners.
P5.js supports a number of functions to help draw different shapes. For more, please see the reference section of p5js.org
Ellipse, Triangle and Rectangles
ellipse(x,y,a,b); - draws an ellipse at position x,y that is a units wide, b units tall.
rect(x,y, a,b) - draws a rectangle at x,y that is a units wide, b units tall.
triangle(x1,y1, x2,y2, x3,y3) - draws a triangle where the corners are defined as the three points (x1,y1), (x2,y2) and (x3,y3)
The order of the drawing depends on the order of the function calls. Each shape is drawn in order. If there should be an overlap, the later shape is drawn over the earlier shape. The order that you draw can have a big impact on what you see so sequencing your instructions correctly is really important.
colours
Colours in p5.js can be defined in the following manner:
greyscale (a single number from 0 to 255). 0 is black, 255 is white, all numbers in between is grey. Bigger numbers will make the grey lighter, smaller numbers will make the grey darker.
rgb (3 numbers. Each number range from 0 to 255). The first number stands for the amount of red light in the colour, the second number for the amount of green light. The third number for the amount of blue light. An RGB value can also be specified by its hex equivalent in a string. Thus, 255,0,255 can also be specified as: "#FF00FF". The final colour is a mix of the 3 lights. (see conversion on how to change from 255,0,255 to #FF00FF)
More details on how colours are specified is given in the Details section below.
There are two different components to each shape that can be coloured. The outline colour (stroke) and the fill colour. To alter the next shapes outline colour, call the stroke(color) function with the colour you want to use before drawing the shape. To change the fill colour, use the fill(color) function before draiwng the shape.
stroke(255,0,0); //red
fill(0,0,255); //blue
ellipse(50,50,80,80);
This will draw a blue circle with a red outline