随机小球

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
body{
overflow: hidden;
}
</style>
<body>
<canvas id="view" width="" height=""></canvas>
</body>

<script type="text/javascript">

//1.初始化获取元素
var canvas = document.getElementById('view');

var ps = canvas.getContext('2d');

//2.获取窗口可视区域宽高
var width = document.documentElement.clientWidth;

var height = document.documentElement.clientHeight;

//3.更新canvas宽高
canvas.width = width;

canvas.height = height;

//4.定义构造函数

function ball(title){

//初始化xy坐标还有半径

this.r = 15;

this.x = this.random(width-this.r);

this.y = this.random(height-this.r);

//初始化颜色

this.color = this.randomColor();

//初始化移动速度

this.speedX = this.random(4);

this.speedY = this.random(6);

//初始化文本

this.title = title || 'Canvas';




}

//5.添加原型方法

ball.prototype = {

random:function(num){

return parseInt(Math.random()*num)+1

},

randomColor:function(){

return 'rgb('+this.random(255)+','+this.random(255)+','+this.random(255)+')'

},


move:function(){

this.x += this.speedX;

this.y += this.speedY;

if(this.x < this.r ){

this.speedX = Math.abs(this.speedX)

}else if(this.x > width-this.r){

this.speedX = -this.speedX

}

if(this.y < this.r ){

this.speedY = Math.abs(this.speedY)

}else if(this.y > height-this.r){

this.speedY = -this.speedY

}

this.render();

},

render:function(){

ps.beginPath();

ps.fillStyle = this.color;

ps.arc(this.x,this.y,this.r,0,2*Math.PI);

ps.fill();

this.fillText();

},

fillText:function(){

ps.font = '16px 微软雅黑';

ps.fillText(this.title,this.x+this.r+2,this.y+this.r/2-2);

}


}

//单独给ball函数添加属性或方法

ball.children = [];

ball.running = 0;

ball.init = function(list){

//拆分成数组

list = list.split(/s+/);


//遍历数组并创建对应的球

for(var i = 0; i<list.length; i++){

// 将实例化的球添加到children中 并且指定文本

this.children.push(new this(list[i]))// this就是ball
}

}

ball.play = function(){

//如果已运行返回
if(this.running) return;

this.running = 1;

var children = this.children;

setInterval(function(){

ps.clearRect(0,0,width,height);

//遍历子元素执行move方法


for(var i = 0; i<children.length; i++){

//执行move方法
children[i].move();

// 遍历所有子元素挨个比较计算距离

for(var j = 0; j<children.length;j++){

//i==j时不比较 因为是同一个球

if(i!=j){

//计算两个球之间的距离

var left = children[i].x - children[j].x;

var top1 = children[i].y - children[j].y;

//取绝对值

// left = Math.abs(left);

top1 = Math.abs(top1);


//限制距离 在100-200之间可以连线

if(left<0 && left>=-200 && top1<=200){

//从当前球画到 另一个

ps.beginPath();

ps.strokeStyle = children[i].color;

ps.moveTo(children[i].x,children[i].y);

ps.lineTo(children[j].x,children[j].y);

ps.stroke();

}


}

}

}


},30);

}

ball.init('Html Css Javascript Jquery Css Javascript Jquery Css Javascript Jquery Css Javascript Jquery PHP Mysql XML Ajax JSONP Cavnas BigPipe Memached Redis CSS3 HTML5');

ball.play();

//var obj = new ball();







</script>

</html>
原文地址:https://www.cnblogs.com/shuaishuaidejun/p/6580383.html