📜 ⬆️ ⬇️

T-fractals on JavaScript Canvas

Today I read celen 's post and was inspired by the beauty of T-fractals. Since I am a little keen on creating raster compositions in JavaScript Canvas, I had an idea to implement the same thing only on the client side by JS, freeing the server from the load.

In the body of the HTML document you need to create a <canvas> :
 <canvas id="canvas"></canvas> 

It is rather peculiar: by default it has a size of 300x150. It is better to set new sizes from javascript.
 var canva = document.getElementById('canvas'); canva.width = window.innerWidth; canva.height = window.innerHeight; var ctx = canva.getContext('2d'); 

Now we define several auxiliary functions.
 function clear() { ctx.clearRect(0, 0, canva.width, canva.height); ctx.fillStyle = 'rgba(0,0,0,1)'; ctx.fillRect(0, 0, canva.width, canva.height); } 

The clear() function clears the entire work area. Why there immediately clearRect and full fill fillRect ? And so for sure .

The following function is responsible for outputting a single pattern of a given size at a specified location. The pattern itself is described using a two-dimensional figure array with the size of NxN, whose elements take on values ​​0 and 1 (0 is a transparent block, 1 is a color block).
 function PrintFigure(x, y, size, style) { var sizeElem = Math.floor(size / N); for (var i = 0; i < N; i++) for (var k = 0; k < N; k++) if (figure[i][k] == 1) { ctx.fillStyle = style; ctx.fillRect(x + i * sizeElem, y + k * sizeElem, sizeElem, sizeElem); } } 

When calculating the coordinates and sizes, you need to be careful and cut off potentially non-integer numbers.

Borders of drawing we will have borders of canvas.
 var MAX_X = canva.width, MAX_Y = canva.height; 

You’ll have to go out a bit to get an even, solid image.
')
And, finally, a function that draws a pattern in a given area, as long as it fits in it [area].
 function CreateTFractal() { clear(); var size = N; var countByX = Math.floor(MAX_X / size), countByY = Math.floor(MAX_Y / size); while ((countByX > 0) && (countByY > 0)) { //      for (var i = 0; i <= countByX; i++) { for (var k = 0; k <= countByY; k++) { PrintFigure(i * size, k * size, size, 'rgba(255, 255, 255, 0.3)'); } // k } // i size *= 2; //      countByX = Math.floor(MAX_X / size), countByY = Math.floor(MAX_Y / size); } } 

Condition And in a while in theory, you can replace it with OR .

demonstration / download HTML-page and JS-code archive

Poiteration image rendering (from left to right and from top to bottom):



It is worth paying a little attention to the possibility to save the image from <canvas> in PNG by javascript:
 window.open(document.getElementById("canvas").toDataURL("image/png"),"tfract_save"); 

The disadvantage of this method is to limit the length of the address string.

That's all. The rest of the code is a banal handling of forms and controls.

Source: https://habr.com/ru/post/145801/


All Articles