Ashik Paul
Ashik Paul

Reputation: 504

how to make a moving line in vanilla javascript?

I am trying to create a rain effect in vanilla javascript. Below is the code that I have tried.

I am updating the y coordinate every interval but the previous line needs to be cleared so that it looks like a falling line effect.

Thank you

var canvas = document.getElementById("DemoCanvas");
var ctx = canvas.getContext("2d");
class Drop {
  constructor() {
    this.x = canvas.width / 2;
    this.y = 0;
    this.yspeed = 10;
  }
  fall() {
    this.y = this.y + this.yspeed;
  }

  show() {
    ctx.moveTo(this.x, this.y);
    ctx.lineTo(this.x, this.y + 10);
    ctx.stroke();
  }
}
if (canvas.getContext) {
  let d = new Drop();

  setInterval(() => {
    d.show();
    d.fall();
  }, 500);
}
<body>
  <canvas id="DemoCanvas" width="1400" height="1400"></canvas>
</body>

Upvotes: 1

Views: 1048

Answers (1)

Just call ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);, also, when calling stroke, you need to first call ctx.beginPath(), all together:

var canvas = document.getElementById("DemoCanvas");
      var ctx = canvas.getContext("2d");
      class Drop{
        constructor(){
          this.x = canvas.width / 2;
          this.y = 0;
          this.yspeed = 10;
        }
        fall(){
          this.y = this.y + this.yspeed;
        }
      
        show(){
          ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
          ctx.beginPath()
          ctx.moveTo(this.x, this.y);
          ctx.lineTo(this.x, this.y+10);
          ctx.stroke();
        }
      }
      if (canvas.getContext) {
        let d = new Drop();
        
        setInterval(()=>{
          d.show();
          d.fall();
        },500);
      }
<body>
    <canvas id="DemoCanvas" width="1400" height="1400"></canvas>
  </body>

Upvotes: 3

Related Questions