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>

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页