<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<canvas id="canvas" width="400" height="300" style="border:1px dashed red">请使用chrome或者IE9</canvas>
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
//设置小球的属性
var x = 20;
var y = 20;
var r = 20;
//定义小球每次的位移
var mx = 1;
var my = 1;
//定义绘制小球的函数
function drawBall(){
context.clearRect(0,0,canvas.width,canvas.height);
context.beginPath();
context.arc(x,y,r,Math.PI*2,0,true);
context.fillStyle = "#ABCDEF";
context.fill();
context.closePath();
}
//定义小球移动的函数
function move(){
if(x>=canvas.width-r){
mx = -1;
}
if(x<=r){
mx = 1;
}
if(y>=canvas.height-r){
my = -1;
}
if(y<=r){
my = 1;
}
x = x+mx;
y = y+my;
drawBall();
//绘制动画函数,一上来先绘制一帧,绘制结束后马上调用这个回调函数
//一直到动画绘制完毕
window.requestAnimationFrame(move);
}
window.requestAnimationFrame(move); //W3C的标准
//火狐:mozRequestAnimationFrame()
//谷歌:webkitRequestAnimationFrame()
//IE: msRequestAnimationFrame()
</script>
</body>
</html>