Search code examples
canvasrotationline

Redraw a line around a point in a canvas


I am having some issues. I want to fill the canvas with multiple lines around a specific canvas point. The result should be a circle (yellow sun) at the right-middle corner surrounded with some sun beams. The result should look somewhat like the old Japanese flag for instance. My main problem is to draw a line and copy it multiple times. :(


Solution

  • You said your problem is drawing a line and copy it multiple times
    That sound like just a loop drawing lines, it could be an actual for loop or just with a setInterval or the combination of both to animate it a bit.

    Here are a few ideas:

    • On this, we draw lines from the center straight out, just using some trigonometry and some randomness.

      const canvas = document.getElementById("c");
      canvas.width = canvas.height = 140;
      const ctx = canvas.getContext("2d");
      ctx.translate(canvas.width / 2, canvas.height / 2)
      
      let r = 20;
      let bars = 90;
      function draw() {
        ctx.clearRect(-100, -100, 200, 200)
      
        for (var i = 0; i < 360; i += (360 / bars)) {
          var angle = i * ((Math.PI * 2) / bars);
          var x = Math.cos(angle) * r;
          var y = Math.sin(angle) * r;
          var v = Math.random() + 2;
      
          ctx.beginPath();
          ctx.moveTo(x, y);
          ctx.lineTo(x * v, y * v)
          ctx.stroke();
        }
      }
      
      setInterval(draw, 100)
      <canvas id="c"></canvas>

    • This other one the lines are straight down and we later rotate the canvas

      const canvas = document.getElementById("c");
      canvas.width = canvas.height = 140;
      const ctx = canvas.getContext("2d");
      ctx.translate(canvas.width / 2, canvas.height / 2)
      
      let r = 20;
      var i = 0;
      
      function draw() {
        ctx.beginPath();
        ctx.moveTo(r, -60);
        ctx.lineTo(r, 60)
        ctx.stroke();
        ctx.rotate(0.6)
        if (i++ > 20) {
          ctx.clearRect(-100, -100, 200, 200)
          i = 0
        }
      }
      
      setInterval(draw, 200)
      <canvas id="c"></canvas>