Search code examples
javascriptjqueryhtmlraphael

How to draw a tower make of rectangles going from small to large using raphael graphics using a for loop?


I don't get how to draw a tower using a for loop 8 times? so the end result will look like this enter image description here

Here is what I Have

setup = function() {
  paper = Raphael ('pyramid', 500,500)


  for (i=1; i <= 8; i+=1){


rect = paper.rect(80,i*5,i*15,5)
 }
$(document).ready(setup)

Solution

  • Being CH = Canvas Height and CW = Canvas Width,

    Each block have Height H = CH/8. For the first, top = 0, bottom = H. For the 2nd, top = H, bottom = H * 2. So for n, top = (n - 1) * H.

    The width of the last is CW, decreasing by a variance V each step, so Width W = CW - (8 - n) * V. We can set V = CW/8 for instance. The block is centered, so Left = (CW - W) / 2.

    cw = 180;
    ch = 180;
    s = 8;
    paper = Raphael('pyramid', cw, ch)
    for (n = 1; n <= s; n += 1) {
      h = ch / s;
      t = h * (n - 1);
      v = cw / s;
      w = cw - (s - n) * v;
      l = (cw - w) / 2;
      paper.rect (l, t, w, h);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.3.0/raphael.min.js"></script>
    <div id="pyramid"></div>