1

我希望让处理程序 OnClick 成为随机实例,而不是需要用户交互。

// add the canvas in
  document.body.appendChild(mainCanvas);
  document.addEventListener('mouseup', createFirework, true);
  document.addEventListener('touchend', createFirework, true);

// and now we set off
    update();
  }

  /**
   * Pass through function to create a
   * new firework on touch / click
   */
  function createFirework() {
        createParticle();
  }

谢谢!:)

4

2 回答 2

0

只需从 Jonathan 扩展一个好的解决方案:您不需要创建 eventListeners 递归 randFunc() 会随机调用,直到您退出浏览器。

我猜你需要实现一种方法来停止该功能。这是一种解决方案:

     var stopFW = false;
        function randFunc () {
             // stop execution           
            if (stopFW) return;
            console.log("Called myself..." + new Date());
            // And then instruct this function to be called between 0 and 10 seconds
            setTimeout(randFunc, Math.ceil(Math.random() * 10) * 1000);
        }

        function stopFireWork() {
            stopFW = !(stopFW);
            console.log(stopFW);
        }

<body onload="randFunc()">    
    <button onclick="stopFireWork()">Stop Firework</button>
</body>
于 2012-12-27T21:34:20.273 回答
0

调用函数本身并不太难:

// This function executes itself the first time immediately
(function randFunc () {
    // We output some information to the console
    console.log("Called myself..." + new Date());
    // And then instruct this function to be called between 0 and 10 seconds
    setTimeout(randFunc, Math.random() * 10 * 1000);
}());​​

演示:http: //jsfiddle.net/8tZEu/2/

于 2012-12-27T20:24:44.930 回答