canvas

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>requestAnimationFrames</title>
<style media="screen">
canvas {
box-shadow: 0 0 10px black;
margin: 30px;
}
</style>
</head>
<body>

<canvas id="canvas" width="500" height="500">
您的浏览器不支持canvas
</canvas>

</body>
<script type="text/javascript">

// 获取元素和上下文对象
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

// 创建小球对象
var ball = {
x: 50,
y: 50,
r: 30,
speedX: 5,
speedY: 3,
draw: function () {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
},
move: function () {
this.x += this.speedX;
this.y += this.speedY;

if (this.x >= 500 - this.r || this.x <= this.r) { this.speedX *= -1; }
if (this.y >= 500 - this.r || this.y <= this.r) { this.speedY *= -1; }
}
};

// 通过定时器,让小球进行移动
// setInterval(function () {
// ctx.clearRect(0, 0, 500, 500);
//
// // 移动小球,然后绘制
// ball.move();
// ball.draw();
// }, 100);


// function gameloop() {
// ctx.clearRect(0, 0, 500, 500);
// ball.move();
// ball.draw();
//
// // 使用timeout实现interval的功能,实际上就是自己调用自己
// setTimeout(gameloop, 10);
// }
// gameloop();


var a = null;
function gameloop() {

ctx.clearRect(0, 0, 500, 500);
ball.move();
ball.draw();

// requestAnimationFrame 使用帧,进行动画效果,保证每隔一帧执行一次
// 两次执行中间的时间间隔不确定,又电脑性能来决定
// 如果使用帧动画,需要注意: 利用 取余运算 进行时间的选取,称为每隔多少帧执行一次
// 取消动画的方式和 interval 、 timeout 一样,都有单独的方法,都有把返回值做参数
a = window.requestAnimationFrame(gameloop);
}
gameloop();

// 取消帧动画
document.onclick = function () {
window.cancelAnimationFrame(a);
};

 


</script>
</html>

posted @ 2016-11-29 22:00  csw123  阅读(128)  评论(0编辑  收藏  举报