Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

HTML5 Canvas – Draw triangles in a straight line with a rotation on each following triangle using a loop

I’m trying to draw triangles on 5 different "planes" using a loop. The loop is working and the triangles are being drawn as I want them to. However, the triangles are not drawn in a straight line. They go up and down.

  let c = document.querySelector("canvas").getContext("2d");
  let objects = [2, 4, 6, 8, 10];

  for (let y = 0; y < 5; y++) {
    let object = objects[y];
    let angle = 0;
    for (let x = 0; x < object; x++) {
      c.setTransform(1, 0, 0, 1, 10 + x * 100, y * 100);
      c.rotate(angle * (Math.PI / 180));

      c.beginPath();
      c.moveTo(20, 0);
      c.lineTo(0, 40);
      c.lineTo(40, 40);
      c.closePath();
      c.fill();
      angle += 20;
    }
  }

Codepen: https://codepen.io/leoss/pen/xxJrwgW

The idea is for each triangle to be drawn out on the y-coordinate y*100. If I remove the ctx.rotate-line they are printed out in a straight line, but then I wouldn’t get the rotation I want.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve tried doing it using ctx.translate instead of ctx.setTransform, but I can’t get it working.

>Solution :

You need to rotate from the center of the triangle, not the top-left corner. Wrap your rotation in a pair of translations to do this:

  c.translate(20,20)
  c.rotate(rot * (Math.PI / 180));
  c.translate(-20,-20)
  let c = document.querySelector("canvas").getContext("2d");
  let objects = [2, 4, 6, 8, 10];

  for (let y = 0; y < 5; y++) {
    let object = objects[y];
    let rot = 0;
    for (let x = 0; x < object; x++) {
      c.setTransform(1, 0, 0, 1, 10 + x * 100, y * 101)
      c.translate(20,20)
      c.rotate(rot * (Math.PI / 180));
      c.translate(-20,-20)

      c.beginPath();
      c.moveTo(20, 0);
      c.lineTo(0, 40);
      c.lineTo(40, 40);
      c.closePath();
      c.fill();
      rot += 20;
    }
  }
<canvas width="1000" height="500" style="border: 1px solid black"></canvas>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading