如何在香草javascript中制作移动线?

我正在尝试在香草 javascript 中创建下雨效果。下面是我尝试过的代码。


我在y每个间隔更新坐标,但需要清除前一行,使其看起来像下降线效果。


谢谢


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>


喵喵时光机
浏览 154回答 1
1回答

一只甜甜圈

只需调用ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);,同样,调用时stroke,您需要先调用ctx.beginPath(),所有这些:var canvas = document.getElementById("DemoCanvas");&nbsp; &nbsp; &nbsp; var ctx = canvas.getContext("2d");&nbsp; &nbsp; &nbsp; class Drop{&nbsp; &nbsp; &nbsp; &nbsp; constructor(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.x = canvas.width / 2;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.y = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.yspeed = 10;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fall(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.y = this.y + this.yspeed;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; show(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.beginPath()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.moveTo(this.x, this.y);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.lineTo(this.x, this.y+10);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.stroke();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; if (canvas.getContext) {&nbsp; &nbsp; &nbsp; &nbsp; let d = new Drop();&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; setInterval(()=>{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d.show();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d.fall();&nbsp; &nbsp; &nbsp; &nbsp; },500);&nbsp; &nbsp; &nbsp; }<body>&nbsp; &nbsp; <canvas id="DemoCanvas" width="1400" height="1400"></canvas>&nbsp; </body>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript