<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
<canvas id="canvas" style="border:1px solid #aab;display:block;margin:50px auto;">
不支持canvas,请换浏览器
</canvas>
<script type="text/javascript">
var ball={x:512,y:150,r:10,g:1,vx:-4,vy:0,color:"#ccff66"}
window.onload=function(){
var canvas=document.getElementById("canvas");
canvas.width=800;
canvas.height=800;
var context=canvas.getContext("2d");
setInterval(
function(){
render(context);
update();
}
,
25
);
}
function update(){
ball.x+=ball.vx
ball.y+=ball.vy
ball.vy+=ball.g
if(ball.x <= ball.r){
ball.x = ball.r
ball.vx = - ball.vx
}
if(ball.x >= 800-ball.r){
ball.x = 800-ball.r
ball.vx = - ball.vx
}
if(ball.y >= 800- ball.r){
ball.y = 800- ball.r
ball.vy = - ball.vy
}
if(ball.y <= ball.r){
ball.y=ball.r
ball.vy=-ball.vy
}
console.log(ball.y,ball.vy)
}
function render(cxt){
cxt.clearRect(0,0,cxt.canvas.width,cxt.canvas.height);
cxt.fillStyle=ball.color;
cxt.beginPath();
cxt.arc(ball.x, ball.y,ball.r,0,2*Math.PI)
cxt.closePath()
cxt.fill()
}
</script>
</body>
</html>
小球不会来回的弹是怎么回事