我正在编写一个脚本来模拟球的抛物线运动。我不明白我错在哪里,它适用于jquery。我认为这是框架中的一个问题。
<html>
<head>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var x = 100;
function init() {
setInterval("draw()", 1);
}
function draw() {
ctx.beginPath();
ctx.arc(x, motoPar(x + 2, 0, 100, 100), 30, 0, Math.PI * 2);
ctx.stroke();
}
function motoPar(x, x0, Vx, Vy){
var y;
var g = 3;
y = -1/2 * g * (x * x) / (Vx * Vx) + Vy / Vx * x;
return y;
}
</script>
</head>
<body>
<canvas id="myCanvas" width="600" height="600" style="border: 1px solid black;">
Your browser does not support the HTML5 canvas tag.
</canvas>
</body>
</html>
答案 0 :(得分:0)
我能够让你的球移动,但不是抛物线。
1 在window.onload中包装您的入门代码并在其中调用init()(尽管将c,ctx和x的var声明保持为全局变量 - 即在window.onload function)):
var c, ctx, x;
window.onload = function() { // <-- invoked when page ready
c = document.getElementById("myCanvas"); // c is null if DOM isn't done
ctx = c.getContext("2d");
x = 100;
init(); // <-- make sure to call :)
}
2 将标识符draw
传递给setInterval(函数名也是变量)
setInterval(draw, 1);
3这会让你得到一个球,但它不会移动。就动议而言,我会把它留给你,但是我把++x
扔到了draw()
函数的中间,这至少让球滑向右下方