p5.j​​s mousePressed线动画

时间:2018-05-14 09:23:52

标签: javascript p5.js

在p5.js中,我正在尝试创建一个动画,当按下鼠标时,线条的底点平滑(每帧5px)移动到画布的左下角。我可以通过lines.align让他们达到他们需要达到的程度,但他们会立即移动到那里而不是动画。

    let lines = []

    function setup() {
      createCanvas(600, 400);
      for(let i = 0; i < 150; i++) {
          lines[i] = new Line(random(600), 0, random(600), 400, random(149,212), random(89, 146), 1);
        }
    }

    function draw() {
      background(32, 44, 57);
      for(let i = 0; i < lines.length; i++){
        lines[i].show();
      }
    }

    function mousePressed() {
      for(let i = 0; i < lines.length; i++){
        lines[i].align();
      }
    }

    class Line {
      constructor(xStart, yStart, xFinish, yFinish, g, b, w) {
        this.xStart = xStart;
        this.yStart = yStart;
        this.xFinish = xFinish;
        this.yFinish = yFinish;
        this.g = g;
        this.b = b;
        this.w = w;
      }

      show() {
        stroke(242, this.g, this.b);
        strokeWeight(this.w);
        line(this.xStart, this.yStart, this.xFinish, this.yFinish);
      }

      align() {
        while (this.xFinish > 0) {
          this.xFinish = this.xFinish - 5;
        }
      }
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>

1 个答案:

答案 0 :(得分:2)

您正在使用阻止while循环,这就是为什么在视觉上您会看到从线条跳转的原因&#39;开始结束职位。

一种选择是使用条件并增加draw()中的值:

&#13;
&#13;
let lines = []

    function setup() {
      createCanvas(600, 400);
      for(let i = 0; i < 150; i++) {
          lines[i] = new Line(random(600), 0, random(600), 400, random(149,212), random(89, 146), 1);
        }
    }

    function draw() {
      background(32, 44, 57);
      for(let i = 0; i < lines.length; i++){
        lines[i].align();
        lines[i].show();
      }
    }

    class Line {
      constructor(xStart, yStart, xFinish, yFinish, g, b, w) {
        this.xStart = xStart;
        this.yStart = yStart;
        this.xFinish = xFinish;
        this.yFinish = yFinish;
        this.g = g;
        this.b = b;
        this.w = w;
      }

      show() {
        stroke(242, this.g, this.b);
        strokeWeight(this.w);
        line(this.xStart, this.yStart, this.xFinish, this.yFinish);
      }

      align() {
        if (this.xFinish > 0) {
          this.xFinish = this.xFinish - 5;
        }
      }
    }
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.min.js"></script>
&#13;
&#13;
&#13;

您可能还需要查看lerp()以在开始和结束位置之间进行插值。

此外,如果您需要更多控制时间/缓和/等,您可以使用TweenLite之类的东西为您进行插值。 (虽然首先要手动增加值/插值/补间,这是一个很好的练习)