
There’s something captivating about triangles. These simple three-sided shapes can, when combined in creative ways, result in strikingly beautiful patterns, but the beauty of it all is that you can create such designs using JavaScript and some hacky code.
A few years back, while exploring React, I ventured into building a rudimentary Photoshop-like interface with layers and masks. Each layer could take on the color from any other layer or use another layer as a mask.
So when generating triangles the most bruteforce way I came up with at the time was to do it horizontally based on the size of the triangle, and that meant every other triangle was up side down so they chained together, this meant that in code every other triangle needed to be drawn inverted.
const drawATriangle = (ctx, x = 0, y = 0, size = 10, fill = 'red', layer) => {
if (layer.everyOther && layer.everyOther === true && (x % size) * 2 === 0) {
count++;
return;
}
ctx.beginPath();
if (count % 2 === 0) {
ctx.moveTo(x, y + size);
ctx.lineTo(x + size / 2, y);
ctx.lineTo(x + size, y + size);
} else {
ctx.moveTo(x, y);
ctx.lineTo(x + size, y);
ctx.lineTo(x + size / 2, y + size);
}
ctx.fillStyle = fill;
ctx.strokeStyle = fill;
ctx.stroke();
ctx.closePath();
ctx.fill();
count++;
};
The concept was simple and quite crude… It all starts out with a base image you want to take your colors from then a circle layer or any kind of shape, This circle acts as a mask to the rest of the images. While you can have as many as you like, one was enough for me. Each background is rendered via triangles. Depending on the size of the triangles and the spot from which it took the color from the original image, you get a visually appealing triangle background encased within the circle.
It copies the center point of the triangle based on its size and renders it instead of the image. The finished image is a multi-layered piece of triangle art.
This project proved an excellent foray into prototyping with JavaScript, although I never finished the project, you can try out the janky alpha version at your own discourse.
- You can use the mask round mask here: Image Mask
- Check it out here in the most yankies form Triangle Canvas Art
- You can move your images around by clicking and holding on the tiny layer images
- double clicking on a layer will move focus to that layer
- The order of the layers arent actually important, but the followMaskFromLayer and copyColorsFromLayer need to be set correct for each image.
- In my example image, first background layer has followMaskFromLayer set to 1, copyColorsFromLayer set to itself, layer 0
- Secong layer copys the colors from layer 0 and has itself as mask
- Third layer uses itself as color but also the mask
- Fourth layer uses itself as color aswell and the mask altough it could omit a mask as its a transparent png.
Buy Me a Coffee