-
1Step 1
First, we need function to create dots which will be used for creating triangles. Easiest way is to create some dots by random. We gonna need width and height of canvas and number of dots and we can create array of random dots that will fit on canvas.
var width = 800; var height = 600; var no = 10; var dots = []; for (var i = 0; i < no; i++) { dots.push([Math.random() * width, Math.random() * height]); }
-
2Step 2
After creating dots we’ll use Delaunay algorithm to connect dots to triangles. From wikipedia:
In mathematics and computational geometry, a Delaunay triangulation for a set P of points in a plane is a triangulation DT(P) such that no point in P is inside the circumcircle of any triangle in DT(P). Delaunay triangulations maximize the minimum angle of all the angles of the triangles in the triangulation; they tend to avoid skinny triangles. The triangulation is named after Boris Delaunay for his work on this topic from 1934.
There is a nice JavaScript implementation for that done by ironwallaby. That module and algorithm are core of what we gonna do, everything else is just a makeup.
var triangles = Delaunay.triangulate(dots);
-
3Step 3
We’ll use canvas to draw triangles, so you’ll need canvas element in your html file, something like this:
<canvas id="triglici"></canvas>
-
4Step 4
Function for drawing triangles is pretty simple:
for (var i = 0; i < triangles.length; i += 3) { ctx.beginPath(); ctx.moveTo(dots[triangles[i]][0], dots[triangles[i]][1]); ctx.lineTo(dots[triangles[i + 1]][0], dots[triangles[i + 1]][1]); ctx.lineTo(dots[triangles[i + 2]][0], dots[triangles[i + 2]][1]); var color = 'rgba(' + parseInt(Math.random() * 255) + ',' + parseInt(Math.random() * 255) + ',' + parseInt(Math.random() * 255) + ', 1)'; ctx.closePath(); ctx.fillStyle = color; ctx.lineWidth = 0.5; ctx.strokeStyle = color; ctx.stroke(); ctx.fill(); }
-
5Step 5
Visit http://workshop.rs/2015/12/javascript-art-triangles/ for more details
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.