Let’s start with a simple illustration



portal

😔 principle

Sine function: amplitude * sin(frequency * x) + displacement

We can animate the control curve by changing the amplitude and frequency of the function.


😈 began

Define a Wave class

` ` `

class Wave {

  constructor(color) {
    this.t = 0;
    this.step = w / 300;
    this.color = color;
This. Speed = 0.1;
    this.a = 30;
    this.f = 20;
    this.d = 20;
  }
  caculate(x) {
    this.amplitude = this.a;
    this.frequency = this.f * (1 / w);
    this.displacement = this.d;
    // A*sin(Bx + C) + D
    return (
      this.amplitude * Math.sin(this.frequency * x + this.t) + this.displacement
    );
  }
  render() {
    this.t += this.speed;
    ctx.save();
    ctx.beginPath();
    ctx.translate(0, h / 2);
    ctx.lineWidth = 1;
    ctx.moveTo(0, 0);
    for (let i = this.step; i < w; i += this.step) {
      ctx.lineTo(i, this.caculate(i));
    }
    ctx.lineTo(w, this.caculate(w));
    ctx.lineTo(w, h);
    ctx.lineTo(0, h);
    ctx.fillStyle = this.color;
    ctx.fill();
    ctx.closePath();
    ctx.restore();
  }
}

` ` `

There’s no magic in it, it’s easy to draw a wave.

portal

But for those who feel it at all, the animation is very rigid, almost like a picture being panned. As a person with ideals can not tolerate.


😄 improvement

It is easy to see that the reason for the stiffness is that the crest of the wave is always this high, and it would be OK to change the size of the crest of the wave as well.

Add a little detail, define a value for this.k, and modify it

this.amplitude = this.a;

Instead of

this.amplitude = this.a * sin(((this.t / this.k) * this.k) / 5);

And if you look at this and you’re wondering where this mysterious function came from, the goal is to make the amplitude change, so we multiplied it by a sine function to make the amplitude change as well.


🐔 finally

Simple case implementation



portal


Refer to the link

Codepen. IO/waynecz/pen…

Dribbble.com/shots/36529…

Dribbble.com/shots/37814…