用canvas和js模拟重力小球

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			html,body{
				margin: 0;
			}
			canvas{
				background: ;
			}
		</style>
	</head>
	<body>
		<canvas id="mycanvas" width="" height=""></canvas>
	</body>
	<script type="text/javascript">
	
		canvas=document.querySelector("#mycanvas")
		body=document.querySelector("body")
		ctx=canvas.getContext("2d")
		var gravity=0.8
		var friction=0.9
		window.addEventListener("resize",function(event){
			canvas.width=window.innerWidth
		    canvas.height=window.innerHeight
		})
		
		canvas.width=window.innerWidth
		canvas.height=window.innerHeight
		function Ball(x,y,dx,dy,radius,color){
			this.x=x
			this.y=y
			this.dx=dx
			this.dy=dy
			this.radius=radius
			this.color=color
			
			this.draw=function(){
				ctx.beginPath()
				ctx.arc(this.x,this.y,this.radius,0,Math.PI*2)
				ctx.fillStyle=this.color
				ctx.fill()
			}
			
			this.update=function(){ 
				if(this.y+this.radius+this.dy+gravity>canvas.height){
					this.dy=-this.dy
					this.dy*=friction
					this.dx*=friction
				}else{
					this.dy+=gravity
				}
				if(this.x+this.radius>canvas.width || this.x-this.radius<0)
				{
					this.dx=-this.dx
					this.dy*=friction
					this.dx*=friction
				}
				this.x+=this.dx
				this.y+=this.dy
				this.draw()
			}
		}
		
		var shot=Math.random()*40-20
		
		var ball=new Ball(100,100,shot,10,50,"skyblue")
		function animate(){
			ctx.clearRect(0,0,window.innerWidth,window.innerHeight)
			ball.update()
			requestAnimationFrame(animate)

		}
		
		animate()
	</script>
</html>

在这里插入图片描述
在这里插入图片描述

发布了41 篇原创文章 · 获赞 3 · 访问量 4620

猜你喜欢

转载自blog.csdn.net/fesfsefgs/article/details/100576477