Javascript:计算平均速度或速度

时间:2015-11-21 18:11:46

标签: javascript canvas

我正在学习基础物理,我正在尝试将这个概念应用到编程中:https://www.khanacademy.org/science/physics/one-dimensional-motion/displacement-velocity-time/v/calculating-average-velocity-or-speed

您可以在6:00正好看到公式。

我希望球以平均速度移动到300px。所以我试图以某种方式实际应用视频中的信息。因此,虽然我正在学习物理学的所有基础知识,我也将其应用于编程。这是我的第一次尝试:

Jsfiddle:http://jsfiddle.net/1phfkb7s/3/

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var direction = 200;
var displacement = 5;
var time = 10;


function render() {
    ctx.clearRect(0, 0, 1000, 1000);
    ctx.beginPath();
    ctx.arc(displacement - direction / time, 75, 30, 0, Math.PI * 2);
    ctx.stroke();

    displacement += 1;
    requestAnimationFrame(render);
}

render();

这是公式:

https://www.google.ch/search?q=velocity+formula&espv=2&rlz=1C1TEUA_enCH660CH660&biw=1366&bih=667&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjt2JXXkaLJAhVIWBQKHdXJCckQ_AUIBigB#imgrc=GsRnur1vRdqEyM%3A

1 个答案:

答案 0 :(得分:2)

displacement += 1;是错误的,因为它只是每次迭代将球移动一个像素。由于您正在使用requestAnimationFrame,因此您需要添加时间感来计算球在任何位置的位置。



var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var distance = 300;    // you said 300 pixels, not 200
var position = 5;      // renamed those as well for clarity
var totalTime = 10;    //
var startTime = new Date();  // the time at which the code starts

var out = document.getElementById('o');

function render() {
    ctx.clearRect(0, 0, 1000, 1000);
    ctx.beginPath();
    ctx.arc(position, 75, 30, 0, Math.PI * 2);  // we only need the position
    ctx.stroke();

    // here we calculate the next step based on:     
    var expired = (new Date() - startTime) / 1000;  // the expired time in seconds
    position = expired * distance / totalTime;      // multiplied by the "step per second"
  
    out.innerHTML = "Seconds: " + Math.floor(expired) + "<br>Position: " + Math.floor(position);
  
    requestAnimationFrame(render);
}

render();
&#13;
<canvas id='canvas' height='120' width='600'></canvas>
<p id="o"></p>
&#13;
&#13;
&#13;

displacement += 1只有在您使用setInterval或其他内容每秒更新一次画布时才有意义:

&#13;
&#13;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var distance = 300;    // you said 300 pixels, not 200
var position = 0;      // renamed those as well for clarity
var totalTime = 10;    //

var out = document.getElementById('o');

function render() {
    ctx.clearRect(0, 0, 1000, 1000);
    ctx.beginPath();
    ctx.arc(position * (distance / totalTime), 75, 30, 0, Math.PI * 2);  // we only need the position
    ctx.stroke();

    position++;
}

setInterval(render, 1000);
&#13;
<canvas id='canvas' height='120' width='600'></canvas>
<p id="o"></p>
&#13;
&#13;
&#13;