Shape and Interactivity
We looked at how to implement mouse interactivity and transformations in sketches before starting pattern creation with p5.js.The Custom Shape
Similar to the HSB colour wheel created in the previous
exercises, the spiky custom shape is created
with the beginShape()
, vertex()
, and endShape()
functions. The TRIANGLE_FAN
constant and a for
loop draws the spikes of the shape. The code for this custom shape is almost similar to the code for
the colour wheel except the segment has no fill colour and has a border around it instead. The starting vertex coordinates is not followed
by a series of vertices but by lines drawn using the line()
function. Transformations are also applied to this sketch.
The coordinate system is moved to the centre of the canvas.
function setup() {
createCanvas(500, 500);
background(224);
centerX = width/2;
centerY = height/2;
}
function draw() {
background(224);
push();
translate(centerX, centerY);
beginShape(TRIANGLE_FAN);
vertex(0, 0);
for (let i = 0; i <= TWO_PI; i += stepAngle) {
let vx = (radius * cos(i));
let vy = (radius * sin(i));
strokeWeight(2);
stroke(0);
line(0, 0, vx, vy);
}
endShape();
pop();
}
Mouse Interactivity
In this exercise, the current mouse position controls the radius and the number of spikes
of the custom shape. The mouseX
coordinate is scaled from a value in the range of
0 to the right edge of the window (width
) to a range between -200 and 200. The resulting
value determines the radius of the custom shape. The mouseY
coordinate is scaled from a range
between 0 and the bottom edge of the window (height
) to a value in the range of 12 and 90. The resulting
value is the number of spikes (numOfSegments
). The angle at which a spike is drawn is the quotient of TWO_PI
divided by
numOfSegments
. TWP_PI
is used in this exercise as the angleMode()
is set to default, which is RADIIANS
. The following lines of code are included in the
draw()
function.
radius = map(mouseX, 0, width, -200, 200);
numOfSegments = map(mouseY, 0, height, 12, 90);
stepAngle = TWO_PI/numOfSegments;