## How the trianglfier works

This technical post will be all about how the recently released Image Trianglfier works.

The visible <img /> element that shows the original image has a function called drawimage() attached to it's load event such that every time a new image is selected, it updates the first of two invisible <canvas> elements:

The above code takes the newly loaded image, calculates new dimensions for the image if either side of the image exceeds 1000 pixels, and draws it to the imagecache canvas.

When the render button is clicked, a second <canvas> with an id of main is put to work:

After grabbing a few references to the main canvas (the one we want to draw the image on) and the imagecache canvas (the one with the scaled original image on it), we then extract the pixeldata of the imagecache canvas on line #5 of the gist so that we can use it to out colours for each triangle later.

We then enter a for loop and start drawing triangles. A triangle is drawn by picking 3 random points within a box with a diameter set by the trianglesize setting, and setting these to be the 3 vertices. The central point of the box is picked on lines #17 and #18, and the 3 points are picked on lines #20 through #33.

The colour of the triangle is also set at this point by averaging the colour in a box centred on the central point we picked on lines #17 and #18. This boxes size is set by the coloursampleradius setting. The algorithm is passed the pixeldata we extracted earlier, along with the canvas size, the coordinates of the centralpoint, and the box's diameter and calculates the average by simply adding up all the colour components of each pixel in the box and dividing it by the number pixels it added up the components of. This algorithm is not particularly optimised and is one of the main causes for the hanging that occurs during the rendering process. This algorithm can be found here.

After the colour and point coordinate calculations, all that is left to do is draw the triangle itself. This is done on lines #36 to #42.

After all the triangles have been drawn, the rendering is complete. The finished image is then converted into a jpeg image is displayed on the right hand side.