7

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.

1 Answer 1

8

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/

1
  • There it is, I tried a lot of things and as I said, couldn't reach such a simple conclusion, sometimes you need others to give you a little push so you can keep on going forward. Thank you so much Dec 19, 2015 at 17:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.