Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to build a pyramid with squares

I'm trying to build a pyramid using squares in HTML5 Canvas, I have an algoritm that is half working, the only problem is that after three days and some lack of math abilities I haven't been able to find the proper formula.

Here is what I have, check the code comments so you can see what part of the algorithm we have to change.

 var canvas = document.getElementById('canvas');
 var ctx = canvas.getContext('2d');
 var W = 1000; var H = 600;
 var side = 16;

 canvas.width = W;
 canvas.height = H;

        function square(x, y) {
            ctx.fillStyle = '#66FF00';
            ctx.fillRect(x, y, side, side);
            ctx.strokeStyle = '#000';
            ctx.strokeRect(x, y, side, side);
        }

        function draw() { 
            ctx.fillRect(0, 0, W, H);
            ctx.save();

            for(var i = 0; i < 30; i++) {   
                for(var j = 0; j < i + 1; j++) {
                    square(
                        //Pos X    
                        //This is what we have to change to
                        //make it look like a pyramid instead of stairs
                        W / 2  - ((side / 2) + (j * side)),


                        //Pos Y
                        side * (i + 1)
                    );
                }
            }

            ctx.restore();
        }

        //STARTS DRAWING
        draw();

This is the code working in jsfiddle so we can try it:

https://jsfiddle.net/g5spscpu/

The desired result is:

enter image description here

Well, I would love if someone could give me a hand, my brain is burning.

like image 805
Juan Bonnett Avatar asked Dec 19 '15 17:12

Juan Bonnett


1 Answers

You need to use the i index in the formula for X position with:

W/2 - ((side / 2) + ((j - i/2) * side))

see https://jsfiddle.net/9esscdkc/

like image 182
6502 Avatar answered Oct 21 '22 22:10

6502