javascript - 为什么在这行代码中乘以0.002 : new Date(). getTime() * 0.002;

标签 javascript canvas requestanimationframe

<分区>

下面代码中乘以0.002有什么特殊用途吗?

var time = new Date().getTime() * 0.002;

此代码摘录自 here .我还提供了下面的完整代码:

window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       || 
          window.webkitRequestAnimationFrame || 
          window.mozRequestAnimationFrame    || 
          window.oRequestAnimationFrame      || 
          window.msRequestAnimationFrame     || 
          function(/* function */ callback, /* DOMElement */ element){
            window.setTimeout(callback, 1000 / 60);
          };
})();
var canvas, context;

init();
animate();

function init() {

canvas = document.createElement( 'canvas' );
canvas.width = 256;
canvas.height = 256;

context = canvas.getContext( '2d' );

document.body.appendChild( canvas );

}

function animate() {
    requestAnimFrame( animate );
    draw();
}

function draw() {
    var time = new Date().getTime() * 0.002;
    var x = Math.sin( time ) * 96 + 128;
    var y = Math.cos( time * 0.9 ) * 96 + 128;

    context.fillStyle = 'rgb(245,245,245)';
    context.fillRect( 0, 0, 255, 255 );

    context.fillStyle = 'rgb(255,0,0)';
    context.beginPath();
    context.arc( x, y, 10, 0, Math.PI * 2, true );
    context.closePath();
    context.fill();
}

最佳答案

代码使用 Math.sin( time ) * 96 + 128 作为 x 坐标,使用 Math.cos( time * 0.9 ) * 96 + 128 作为一个 y 坐标。如果 time 是毫秒数(如 new Date().getTime() 是),则 x 坐标和 y 坐标都会随着每个连续的调用,点似乎不会“移动”,而是“任意跳跃”——每秒 60 次,快于眼睛可以追踪的速度。将毫秒数乘以 0.002 会导致点的 x 坐标和 y 坐标以更平滑的方式振荡,(在人眼看来)就像运动一样。

关于javascript - 为什么在这行代码中乘以0.002 : new Date(). getTime() * 0.002;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8321175/

相关文章:

javascript - MediaStream 同时捕获 Canvas 和音频

javascript - 将对象插入 javascript 数组性能异常

javascript - 传递给 requestAnimationFrame 调用的回调的时间错误

JavaScript:For 循环无法正常工作

javascript - Onesignal 插件延迟 JS

javascript - 如何仅使用变换来旋转html Canvas 形状?

javascript - 计算 AnalyserNode 的 smoothingTimeConstant

javascript - 是否可以用 Javascript 编写纯文本?

javascript - javascript 中的无效参数错误

php - 在没有客户端浏览器的情况下将 HTML Canvas 保存为图像