This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center
                            
                        
                    
                
                                已关闭8年。
            
                    
以下代码中乘以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坐标在每次连续调用时都会剧烈波动,并且该点似乎不会“移动”,而是“跳跃”任意”-每秒六十次,比人眼可以追踪的速度快。将毫秒数乘以0.002会导致点的x坐标和y坐标以更加平滑的方式(以人眼的感觉)振荡。

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

10-11 05:57