Line and Shape
The circle pattern created in the previous exercise was used as a basis for developing the line pattern in this exercise. Randomness and random seed were applied to generate the line pattern.The Shape Class
Similar to the circles, the lines drawn on the canvas are created from the Shape
class.
Each line has the following properties.
class Shape {
constructor(_i, _j) {
this.i = _i;
this.j = _j;
this.s = shapeSize;
this.x = this.i * this.s;
this.y = this.j * this.s;
this.sw = 1;
}
}
this.i
and this.j
are index numbers. this.s
is initialised to
the value assigned to the global variable shapeSize
. this.x
and this.y
are offset properties that make sure the lines will be drawn within the canvas. this.sw
refers to the stroke weight of the line and it is initialised to 1. This value changes depending on the current mouse position.
Generating random numbers
The random()
function can be used to add variety to patterns. This function returns a random value of float type. It takes 0, 1, or
two arguments. In this exercise, the numbers 0 and 1 are passed into random()
and whatever value is returned by the function,
the round()
function rounds the random value to the nearest integer.
A "rising" diagonal line is generated if the random value, which is stored in the randomNum
variable, is equal to 0. If it is
equal to 1, a "falling" diagonal line is generated. The diagonal line goes from one corner of
the shape across to the opposite corner.
render() {
push();
translate(this.x, this.y);
col = color(this.i, 0, numOfShapes - this.j);
strokeWeight(this.sw);
stroke(col);
randomNum = round(random(0, 1));
if (randomNum == 0) {
line(0, this.s, this.s, 0);
} else {
line(0, 0, this.s, this.s);
}
pop();
}
Using randomSeed()
We get different sequences of random values because the random()
function is called on each shape object every time
the draw()
function executes. To control randomness, randomSeed()
is added to draw()
so that
random()
would always return the same sequence of random values.
function draw() {
background(0);
randomSeed(10);
shapes.forEach(shape => {
shape.render();
});
}
Stroke Weight
To implement mouse interactivity in the sketch, the stroke weight of each diagonal line
changes according to the current mouse position. The following code is included in the
render()
method after translation.
d = dist(mouseX, mouseY, this.x, this.y);
this.sw = map(d, 0, width, 2, 7);
The dist()
function calculates the distance between the mouse position and the diagonal line. The result is scaled
from a range between 0 and the width to a range between 2 and 7.