我想指出我是初学者。所以,我希望你不要介意我向你的解决方案提问。
我在这里想要构建的是一个球从高处落到地面然后慢慢地,在几次后续弹跳后,球刚刚在画布底部滚动的图形动画。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JavaScript examples</title>
<!-- As a shortcut, I included style information here rather than a separate file -->
<style>
canvas {
border: 1px solid gray;
}
</style>
<!-- incorporate jQuery -->
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<!-- now my written script -->
<script>
$(function(){
// initialise canvas and context
var canvas = document.getElementById('canvas');
// physical variables
var g = 0.1; // gravity
var fac = 0.8; // velocity reduction factor per bounce
var radius = 20; // ball radius
var color = "#0000ff"; // ball color
var intervalId
function initBall() {
// initialise position and velocity of ball
var x = 50;
var y = 50;
var horizontalvelocity = 2;
var verticalvelocity = 0;
}
function drawBall() {
with (context){
clearRect(0, 0, canvas.width, canvas.height); // clear canvas
fillStyle = color;
beginPath();
arc(x, y, radius, 0, 2*Math.PI, true);
closePath();
fill();
};
};
function render() {
// update velocity
verticalvelocity += g; // gravity
// update position
x += horizontalvelocity;
y += verticalvelocity;
// handle bouncing
if (y > canvas.height - radius){
y = canvas.height - radius;
verticalvelocity *= -fac;
}
// wrap around
if (x > canvas.width + radius){
x = -radius;
}
// update the ball
drawBall();
};
function init() {
<!-- get the rendering area for the canvas -->
context = $('#canvas')[0].getContext("2d");
WIDTH = $('#canvas').width();
HEIGHT = $('#canvas').height();
setInterval(update, 1000/60); // 60 frames per second
initBall();
<!-- start animation -->
intervalId = setInterval(render, 10);
}
$(document).ready(init);
</script>
</head>
<body>
<canvas id="canvas" width="700" height="500"></canvas>
</body>
</html>
我似乎无法发现我犯的错误。非常感谢您的想法和解决方案。 :)
答案 0 :(得分:3)
您的问题与范围问题有关:您在所有代码中使用x,y变量,因此它们应该是全局变量。但是你的问题是1)你没有将它们声明为全局变量; 2)当你在initBall中初始化x,y时,你声明了2个x,y的本地变量,这将隐藏x,y全局变量。 / p>
- &GT;添加全局范围:
var x,y ;
(顺便声明也是
var horizontalvelocity = 2;
var verticalvelocity = 0;
)
- &GT;删除
中的var声明function initBall() {
// initialise position and velocity of ball
x = 50;
y = 50;
horizontalvelocity = 2;
verticalvelocity = 0;
}