Home > Mobile >  HTML5 Canvas - Draw triangles in a straight line with a rotation on each following triangle using a
HTML5 Canvas - Draw triangles in a straight line with a rotation on each following triangle using a

Time:01-13

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;
    }
  }

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.

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

CodePudding user response:

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>

  • Related