recipelee
recipelee

Reputation: 1

Generate a triangular pattern using two different symbols

I want to generate a triangular thing like below:

a       (1px)
bb      (2px)
aaa     (3px)
bbbb    (4px)

However, I found that it won’t be triangular if two symbols have different sizes. For example, the result will be:

口
xx
口口口
xxxx

Here is my code:

<html>

<body>
  <script type="text/javascript">
    <!--    

    window.alert("Hello! This website draws a triangular pattern.");
    var height; //the height of the triangular pattern
    var first; //the first symbol that forms the triangle 
    var second; //the second symbol that forms the triangle
    var display;


    height = window.prompt("What is the height of the triangular pattern?")
    first = window.prompt("Please enter a symbol to generate the triangular pattern:")
    second = window.prompt("Please enter another symbol to generate the triangular pattern:")


    h = parseInt(height);

    var i, j;

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

      display = "<p style = \"font-size: " + i + "ex\">";

      for (j = 1; j <= i; j++) {
        if (i % 2 > 0)
          display += first;

        if (i % 2 <= 0)
          display += second;
      }

      display += "</p>";
      document.write(display);
    }
    //-->
  </script>
</body>

</html>

This is an exercise a found online but I forgot the source. I am required to only use a single HTML file to finish the task. I cannot use external CSS.

Simply saying, if first line total used a px, then the second line needs to use 2a px, ignoring the sizes of symbols.

And I want to know how can I make this. Like the below image.

enter image description here

I think it is okay for me to generate the shape reluctantly if the sizes of symbols are nearly same. Hope the code above need not to change if there is no big problem as I want to keep some of my efforts seen.

Upvotes: 0

Views: 130

Answers (1)

Aparajit P Utpat
Aparajit P Utpat

Reputation: 385

Set the line-height to 1px. Change your first statement inside the for loop to below code

display = "<p style = \"font-size: " + i + "ex; line-height: " + i +"px\">";

You will get something like

enter image description here

Upvotes: 1

Related Questions