In this lesson, you will draw a square fractal.
Learn by Doing
To make drawing rectangles a bit easier in this next sketch, see if you can make a different version of the .rectangle(), calling it .centerRectangle() and making it so that instead of passing it the top left corner coordinate, you pass its center, like how the circle method is called.
If you're doing this course step-by-step, and especially if you're in the mentorship program, please be sure to push your work to GitHub when you're done.
A New Method for the Draw Class
// Draw.js
export class Draw {
// ...
centerRectangle(point, w, h, color) {
let xTopLeft = point.x - w / 2;
let yTopLeft = point.y - h / 2;
this.ctx.strokeStyle = color;
this.ctx.strokeRect(xTopLeft, yTopLeft, w, h);
}
// ...
}
This takes the point and moves it up and left so that the context's strokeRect() method can draw it from the top left, but to whoever is using the Draw library, it will be like drawing from the center point of the rectangle.
Fractals
A fractal is a shape that tends to repeat itself. Typically if you look at a portion of a fractal and then zoom in, and look at another portion, it will look very similar.
First, this section will look at a simple fractal, and then in the next lesson, you'll get into a tree fractal.
First off, make the canvas larger at 1000 x 1000. Feel free to go larger, though you may have to zoom out the browser to see everything on your screen. If you do change the size of the canvas to anything other than 1000 x 1000, then just be aware to make the numbers that follow consistently with each other:
// square-fractal.js
import { Point } from './point.js';
import { Draw } from './draw.js';
const BACKGROUND_COLOR = 'gold';
const canvas = document.getElementById('canvas');
const draw = new Draw(canvas);
draw.setHeight(1000);
draw.setWidth(1000);
draw.background(BACKGROUND_COLOR);
const startPoint = new Point(500, 500); // middle point of canvas
function fractal(point, w, h) {
if (w < 2 || h < 2) return;
draw.centerRectangle(point, w, h);
const quarters = [
new Point(point.x - w / 4, point.y - h / 4),
new Point(point.x + w / 4, point.y - h / 4),
new Point(point.x - w / 4, point.y + h / 4),
new Point(point.x + w / 4, point.y + h / 4)
];
quarters.forEach((p) => fractal(p, w / 2.5, h / 2.5));
}
fractal(startPoint, 950, 950);
This draws a large square and then draws four smaller squares in each corner of the square and so on until the size of the squares is lower than 2 pixels.
Summary:
In this lesson, you drew a basic fractal with squares.
Customize this sketch, use other shapes, color it in interesting ways, and make it your own!