网页重力小球动画
网页canvas重力小球动画
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
canvas{
width:100%;
height:100%;
background:lightslategrey;
position:fixed;
top:0;left:0;
}
</style>
</head>
<body>
<canvas></canvas>
<script>
let canvas = document.querySelector("canvas");
let context = canvas.getContext("2d");
let width = canvas.width = canvas.offsetWidth;
let height = canvas.height = canvas.offsetHeight;
let r = 50; //小球半径
let x = 50; //圆心横坐标
let y = 50; //圆心纵坐标
let vx = 2; //默认横向速度
let vy = 0; //默认纵向速度
let g = 0.5; //重力加速度
(function draw(){
//清空画布、重新绘制
context.clearRect(0,0,width,height);
context.beginPath();
vy += g;
x += vx;
y += vy;
//碰到底部
if(y>=height-r){
y=height-r;
vy *= -0.6; //纵向速度方向改变 损耗0.3
vx -= 0.05; //横向速度减少
if(vx<=0){
vx = 0;
}
}
//画实心圆
context.arc(x,y,r,0,Math.PI*2);
context.fill();
requestAnimationFrame(draw);
}())
</script>
</body>
</html>