一个物体以每帧1像素的速度向45度的方向移动,我们把该速度分解成x轴和y轴上的速度vx和vy,物体位于x轴上的边和y轴上的边,与物体的运动轨迹形成一个直角三角形,,三角形的两条邻边恰好落在x、y轴上。事实上,x轴上的直角边等于物体在x轴上所要移动的距离,而y轴上的直角边则是物体在y轴上所要移动的距离。
在已知角度为45度,斜边长为1个像素的情况下,可以利用三角函数计算出vx和vy的数值。
vx和vy的计算公式如下:
vx = Math.cos(angle) * speed;
vy = Math.sin(angle) * speed;
因此可求出vx和vy的值:
radians = 45 * Math.PI / 180;
vx = Math.cos(radians) * 1;
vy = Math.sin(radians) * 1;
代码实现如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no,width=device-width">
<title></title>
<style>
*{margin: 0;padding: 0}
body {
background-color: #eee
}
canvas {
background-color: #fff
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="400">
Your browser does not support HTML5 Canvas.
</canvas>
<script>
(function(){
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded(){
canvasApp();
}
function canvasSupport(e){
return !!e.getContext;
}
function canvasApp(){
let canvas = document.getElementById("canvas");
if(!canvasSupport(canvas)){
return ;
}
// start
let context = canvas.getContext("2d");
drawScreen(canvas, context);
}
// write your codes
function drawScreen(canvas, context){
let ball = new Ball();
let angle = 45;
let speed = 1;
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
let radians = angle * Math.PI / 180;
let vx = Math.cos(radians) * speed;
let vy = Math.sin(radians) * speed;
(function drawFrame() {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
ball.x += vx;
ball.y += vy;
ball.draw(context);
} ())
}
})();
</script>
<script>
function Ball(radius, color) {
if (radius === undefined) {
radius = 40;
}
if (color === undefined) {
color = "#ff0000";
}
this.x = 0;
this.y = 0;
this.color = color;
this.radius = radius;
}
Ball.prototype.draw = function(context) {
context.save();
context.translate(this.x, this.y);
context.fillStyle = this.color;
context.beginPath();
context.arc(0, 0, this.radius, 0, 360 * Math.PI / 180, false);
context.closePath();
context.fill();
context.restore();
}
</script>
</body>
</html>