MDN--canvas--绘制弹跳小球

代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#canvas {
				border: 1px #000 solid;
			}
		</style>
	</head>
	<body>
		<canvas id="canvas" width="600" height="300"></canvas>
		<script type="text/javascript">
			var canvas = document.querySelector('#canvas');
			var ctx = canvas.getContext('2d');
			// 球
			function Ball(x,y,r){
				this.color = '#00f';
				this.r = r;	//半径
				this.x = x;	//坐标
				this.y = y;
				// 速率
				this.vx = 5;
				this.vy = 2;
				
				// 画球
				this.draw = function(){
					ctx.beginPath();
					ctx.fillStyle = this.color;
					ctx.arc(this.x,this.y,this.r,0,2*Math.PI,true);
					ctx.fill();
				}
				
				// 球位置的更新
				this.update = function(){
					// 添加加速度
					this.vy *= .99;
					this.vy += .25;
					// 处理边界问题
					if(this.x + this.vx > canvas.width || this.x + this.vx < 0){
						this.vx *= -1;
						this.x += this.vx;
					}else{
						this.x += this.vx;
					}
					if(this.y + this.vy > canvas.height || this.y + this.vy < 0){
						this.vy *= -1;
						this.y += this.vy;
					}else{
						this.y += this.vy;
					}
					console.log(this.x,this.y);
					this.draw();
				}
				
			}
			
			function anima(){
				// 拖尾效果
				ctx.fillStyle = 'rgba(255,255,255,0.2)';
				ctx.fillRect(0,0,600,300);
				ball.update();
				f = requestAnimationFrame(anima);
			}
			
			var ball = new Ball(20,20,20);
			ball.draw();
			var f;
			var run = false;
			//鼠标控制
			canvas.addEventListener('mousemove', function(e){
				if(!run){
					ctx.clearRect(0,0,600,300);
					ball.x = e.offsetX;
					ball.y = e.offsetY;
					ball.draw();
				}
			});
			
			canvas.addEventListener('click',function(){
				if(!run){
					f = requestAnimationFrame(anima);
					run = true;
				}
			});
			
			canvas.addEventListener('mouseout', function(){
				window.cancelAnimationFrame(f);
				run = false;
			})
			
		</script>
	</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值