直接上代碼啦。。
雙軸加速度:文件名:acceleration1.html。
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>加速度實例1</title>
<style>
#canvas{background-color: #99cc33;}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script type="text/javascript" src="ball.js"></script>
<script type="text/javascript" src="utils.js"></script>
<script type="text/javascript">
window.onload = function(){
var canvas = document.getElementById('canvas'),
context = canvas.getContext("2d"),
ball = new Ball(),
vx = 0,
vy = 0,
ax = 0,
ay = 0;
ball.x = canvas.width/2;
ball.y = canvas.height/2;
window.addEventListener("keydown" , function(event){
switch(event.keyCode){
case 37: //left
ax = -0.1;
break;
case 39: //right
ax = 0.1;
break;
case 38: //up
ay = -0.1;
break;
case 40: //down
ay = 0.1;
break;
}
},false);
window.addEventListener("keyup" , function(){
ax = 0;
ay = 0;
},false);
(function drawFrame(){
window.requestAnimationFrame(drawFrame,canvas);
context.clearRect(0,0,canvas.width,canvas.height);
vx += ax;
vy += ay;
ball.x += vx;
ball.y += vy;
ball.draw(context);
}());
}
</script>
</body>
</html>
效果圖:
角加速度:文件名:acceleration1.html。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>加速度實例2</title>
<style type="text/css">
#canvas{background-color: #99cc33;}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script type="text/javascript" src="arrow.js"></script>
<script type="text/javascript" src="utils.js"></script>
<script type="text/javascript">
window.onload = function(){
var canvas = document.getElementById('canvas'),
context = canvas.getContext("2d"),
mouse = utils.captureMouse(canvas),
arrow = new Arrow(),
vx = 0,
vy = 0,
force = 0.05;
(function drawFrame(){
window.requestAnimationFrame(drawFrame , canvas);
context.clearRect(0,0,canvas.width,canvas.height);
var dx = mouse.x - arrow.x,
dy = mouse.y - arrow.y,
angle = Math.atan2(dy , dx),
ax = Math.cos(angle)*force,
ay = Math.sin(angle)*force;
arrow.rotation = angle;
vx += ax;
vy += ay;
arrow.x += vx;
arrow.y += vy;
arrow.draw(context);
}());
}
</script>
</body>
</html>
效果圖:
參見《HTML5+Javascript動畫基礎》。