<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>hangge.com</title>
<style>
canvas {
cursor: pointer;
border: 1px solid black;
}
</style>
<script>
// 用于表示球的所有细节的Ball函数
function Ball(x, y, dx, dy, radius) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.radius = radius;
this.strokeColor = "black";
this.fillColor = "red";
}
// 这个数组用于保存画布上出现的所有球
var balls = [];
var canvas;
var context;
window.onload = function() {
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
// 每0.02秒绘制一次画布
addBall();
setTimeout(drawFrame, 20);
setTimeout(addBall, 1000);
};
function addBall() {
// 小球半径
var radius = 20;
// 创建新的ball对象
var ball = new Ball(200,20,0,0.2,radius);
// 将其保存在balls数组中
balls.push(ball);
}
function drawFrame() {
context.clearRect(0, 0, canvas.width, canvas.height);//清除画布
// 循环所有的球
for(var i=0; i<balls.length; i++) {
// 把每个球移动到新的位置
var ball = balls[i];
ball.y += ball.dy;
// 添加重力作用的效果,让球加速下落
if ((ball.y+ ball.radius ) < canvas.height) ball.dy += 0.4;//ΔX=at^2
// 如果球碰到底部,反弹回来,但慢慢地减速
if ((ball.y + ball.radius > canvas.height) || (ball.y - ball.radius < 0)) {
ball.dy = -ball.dy+0.5;
if(ball.dy>0){
context.beginPath();
context.fillStyle = ball.fillColor;
// 绘制球
context.arc(ball.x, ball.y, ball.radius, 0, Math.PI*2);
context.lineWidth = 1;
context.fill();
context.stroke();
return;
}
}
context.beginPath();
context.fillStyle = ball.fillColor;
// 绘制球
context.arc(ball.x, ball.y, ball.radius, 0, Math.PI*2);
context.lineWidth = 1;
context.fill();
context.stroke();
}
// 20毫秒后绘制下一帧
setTimeout(drawFrame, 20);
}
</script>
</head>
<body>
<canvas id="canvas" width="400" height="300">
</canvas>
</body>
</html>
js前端画布实现动画小球自由落体
需积分: 50 99 浏览量
2018-05-05
19:43:38
上传
评论
收藏 1KB RAR 举报
qq_42143672
- 粉丝: 0
- 资源: 1