requestanimationframe mouse velocity

时间:2017-05-29 02:54:35

标签: javascript physics

我想在使用requestAnimationFrame时准确测量鼠标移动的速度。这甚至可能吗?我不确定是否可以,因为requestAnimationFrame的帧速率不是常数?

JSFiddle Demo

HTML:

<canvas id="demo" width="400" height="400"></canvas>
<p id="output">Velocity: </p>

CSS:

* {
  margin: 0px;
  cursor: none;
}

#demo {
  border: 1px solid #000;
}

JS:

var canvas = document.getElementById("demo");
var output = document.getElementById("output");
var context = canvas.getContext("2d");
var x = 0;
var y = 0;
var velocity = 0;
var radius = 20;

function draw() {
    context.fillStyle = 'red';
    context.beginPath();
    context.arc(x, y, radius, 0, 2 * Math.PI);
    context.fill();
}

document.addEventListener('mousemove', function(e) {
    x = e.clientX;
    y = e.clientY;
});

function loop() {
    context.clearRect(0, 0, 400, 400);
    draw();
  output.innerHTML = "Velocity: " + velocity;
    requestAnimationFrame(loop);
}
    requestAnimationFrame(loop);

0 个答案:

没有答案