代码之家  ›  专栏  ›  技术社区  ›  InspectorDanno

P5中的定时计数器。js公司

  •  1
  • InspectorDanno  · 技术社区  · 6 年前

    我想在P5设置一个计数器。js。计数器应按顺序打印数字1至10,每次打印之间应有3秒的暂停(此过程总共需要30秒)。

    我在计算 timeElapsed ,由于某种原因,它正在返回 NaN

    var startTime;
    
    function setup() {
      createCanvas(windowWidth, windowHeight); //set canvas to window width and window height
      background("#dc3787"); //background of pink
      var startTime = millis();
      console.log(startTime);
    }
    
    //print i every 3 seconds from 0 - 10
    
    function draw() {
      var timeElapsed = (startTime - millis()); //NaN ?
      console.log(timeElapsed);
    
      for (let i = 0; i <= 10; i++) {
        if (timeElapsed % 3000 === 0) {
          console.log(i);
        }
      }
    }
    
    function windowResized() { //P5 window resize function
      resizeCanvas(windowWidth, windowHeight);
    }
    
    2 回复  |  直到 6 年前
        1
  •  3
  •   Sebastian Speitel    6 年前

    您创建了 startTime 第二次使用 var 在里面 setup() ,因此它只存在于 安装程序() 范围

    draw() 如果不使用 frameRate() ,所以要仍然使用它来更新每个帧,只需节省最后一个数字的打印时间即可( lastPrint )和当前显示的数字( i )并计算每帧的差值。

    当差值为3000或以上时,打印数字的最后一帧至少是3秒前,因此您可以打印下一帧。

    var lastPrint;
    var i = 0;
    
    function setup() {
      createCanvas(windowWidth, windowHeight); //set canvas to window width and window height
      background("#dc3787"); //background of pink
      lastPrint = millis() - 3000;
    }
    
    //print i every 3 seconds from 0 - 10
    
    function draw() {
      var timeElapsed = millis() - lastPrint;
      //console.log(timeElapsed);
    
      if (timeElapsed > 3000) {
        i++;
        console.log(i);
        lastPrint = millis();
      }
    }
    
    function windowResized() { //P5 window resize function
      resizeCanvas(windowWidth, windowHeight);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
        2
  •  0
  •   matski    5 年前

    我没有检查计时的准确性,但您也可以将帧速率锁定为60fps,然后使用以下方法计算等于3秒的特定帧:

    frameCount%180===0 ? i++ : null;
    

    包含要检查的millis()的完整代码:

    let i = 0;
    
    function setup() {
      createCanvas(400,400);
      frameRate(60);
    }
    
    function draw() {
      background(240);
      fill('black');
      textSize(16);
    
      frameCount%180===0 ? i++ : null;
      text(i + '\n' + '(millis: ' +millis()/1000 +')',20,30);
    }