canvas

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<canvas id="canvas" width="600px" height="600px"></canvas>
		<script type="text/javascript">
			var canvas = document.getElementById('canvas');
			console.log(canvas)
			var ctx = canvas.getContext('2d');
			var raf;
			
			var ball = {
			  x: 100,
			  y: 100,
			  vx: 5,
			  vy: 2,
			  radius: 25,
			  color: 'blue',
			  draw: function() {
			    ctx.beginPath();
			    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
			    ctx.closePath();
			    ctx.fillStyle = this.color;
			    ctx.fill();
			  }
			};
			
			function draw() {
			  ctx.clearRect(0,0, canvas.width, canvas.height);
			  ball.draw();
			  ball.x += ball.vx;
			  ball.y += ball.vy;
			  raf = window.requestAnimationFrame(draw);
			}
			
			canvas.addEventListener('mouseover', function(e) {
			  raf = window.requestAnimationFrame(draw);
			});
			
			canvas.addEventListener('mouseout', function(e) {
			  window.cancelAnimationFrame(raf);
			});
			
			ball.draw();
		</script>
	</body>
</html>

  

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>小球运动</title>

	<style type="text/css">
		*{margin:0;padding: 0;}
		body{
			width: 100%;
			height:100%;
			background: #000;
			overflow: hidden;
		}
		#canvas{
			border: 1px solid #eee;
			display: block;
		}
	</style>
</head>
<body>
	<canvas id="canvas"></canvas>
	<script type="text/javascript">

		var mycanvas = document.querySelector("canvas");
		var ctx = mycanvas.getContext('2d');
		mycanvas.width = document.documentElement.clientWidth;
		mycanvas.height = document.documentElement.clientHeight;

		function Ball(x,y) {
			this.x=x;
			this.y=y;
			this.r=30;
			this.color= "rgba("+ parseInt(Math.random()*256) + ","+ parseInt(Math.random()*256) + ","+ parseInt(Math.random()*256)+","+"0.8"+")";
			this.dx = parseInt(Math.random()*8) -2;
			this.dy = parseInt(Math.random()*8) -2;
			ballsArr.push(this);
		}
		
		mycanvas.onmousemove = function(event){
			new Ball(event.clientX,event.clientY)
		}


		Ball.prototype.render=function() {
			ctx.beginPath();
			ctx.arc(this.x,this.y,this.r,0,Math.PI*2,true);
			ctx.closePath();
			ctx.fillStyle = this.color;
			ctx.fill();
			this.r --;
			if(this.r <0){
				this.goudie()
			}
			
		}
		
		Ball.prototype.updata=function() {
			this.x += this.dx;
			this.y += this.dy;
		}
		
		Ball.prototype.goudie=function() {
			for (var i=0;i<ballsArr.length;i++) {
				if(ballsArr[i] === this){
					ballsArr.splice(i,1)
				}
			}
		}
		
		var ballsArr = [];

		setInterval(function(){
			ctx.clearRect(0,0,canvas.width,canvas.height);
			for (var i=0;i<ballsArr.length;i++) {
				ballsArr[i].render();
				ballsArr[i] && ballsArr[i].updata();
			}
		},20)
	
	</script>
</body>
</html>

  

posted @ 2018-08-14 00:20  \面朝阳光/  阅读(132)  评论(0编辑  收藏  举报