码迷,mamicode.com
首页 > 其他好文 > 详细

canvas

时间:2016-11-30 02:10:24      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:调用   text   close   timeout   自己   fill   height   val   bsp   

<!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>

canvas

标签:调用   text   close   timeout   自己   fill   height   val   bsp   

原文地址:http://www.cnblogs.com/csw1364115877/p/6115543.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!