html 代码
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title></title>
- <style>
- *{
- margin: 0;
- padding: 0;
- }
- body{
- overflow: hidden;
- }
- #myCanvas{
- border: 1px;
- background-color: lavenderblush;
- }
- </style>
- </head>
- <body>
- <canvas id="myCanvas"></canvas>
- </body>
- <script type="text/javascript">
- // 获取窗口宽高
- var w = window.innerWidth;
- var h = window.innerHeight;
- var canvas = document.getElementById("myCanvas");
- var ctx = canvas.getContext("2d");
- // 设置画布宽高与窗口宽高一样
- canvas.width = w;
- canvas.height = h;
- // 随机数函数
- function fnRandom(min,max){
- return parseInt((max-min)*Math.random()+min+1)
- }
- function Round(){
- this.r = fnRandom(10,30);
- this.diam = this.r*2;
- // 随机位置
- var x = fnRandom(0,canvas.width - this.r);
- this.x = x<this.r?this.r:x;
- var y = fnRandom(0,canvas.height-this.r);
- this.y = y<this.r?this.r:y
- // 随机速度
- var speed = fnRandom(2,4)/10
- this.speedX = fnRandom(0,4)>2?speed:-speed;
- this.speedY = fnRandom(0,4)>2?speed:-speed;
- // 颜色
- this.color = "orange";
- }
- Round.prototype.draw = function(){
- // 绘制函数
- ctx.fillStyle = this.color;
- ctx.beginPath()
- ctx.arc(this.x,this.y,this.r,0,Math.PI*2,true);
- ctx.closePath();
- ctx.fill();
- }
- Round.prototype.move = function(){
- this.x+=this.speedX;
- if(this.x>canvas.width-this.r){
- // this.speedX*=-1;
- this.x=this.r
- }else if(this.x<this.r){
- this.x=canvas.width-this.r
- }
- this.y+=this.speedY;
- if(this.y>canvas.height-this.r){
- // this.speedY*=-1;
- this.y=this.r
- }else if(this.y<this.r){
- this.y=canvas.height-this.r
- }
- }
- // 使用 Round
- var allRound = [];
- function initRound(){
- // 初始化 30 个圆形对象, 放到数组中
- for(var i = 0 ; i<30;i++){
- var obj = new Round();
- obj.draw();
- obj.move();
- allRound.push(obj);
- }
- }
- initRound();
- var dxdy = []
- function roundMove(){
- ctx.clearRect(0,0,canvas.width,canvas.height);
- // 遍历所有的圆形对象, 让对象自己重绘, 移动
- for (var i = 0 ;i <allRound.length;i++) {
- var round = allRound[i];
- round.draw();
- round.move();
- dxdy[i]={
- dx:round.x,
- dy:round.y
- };
- var dx = dxdy[i].dx;
- var dy =dxdy[i].dy;
- for (var j=0;j<i;j++) {
- var sx = dxdy[j].dx;
- var sy = dxdy[j].dy;
- l = Math.sqrt((dx-sx)*(dx-sx)+(dy-sy)*(dy-sy));
- var C = 1/l*7-0.009;
- var o = C> 0.03 ? 0.03 : C;
- ctx.strokeStyle = 'rgba(0,0,0,'+ o +')'
- console.log(l);
- ctx.beginPath()
- ctx.lineWidth=2;
- ctx.moveTo(dxdy[i].dx,dxdy[i].dy)
- ctx.lineTo(dxdy[j].dx,dxdy[j].dy);
- ctx.closePath()
- ctx.stroke()
- }
- }
- window.requestAnimationFrame(roundMove)
- }
- roundMove();
- </script>
- </html>
canvas
评论
14
喜欢
58
赞
36
评论 ( 14 )
走你
最新评论
来源: http://www.qdfuns.com/article/25573/9569790b8db41d631141ed0d04436d2e.html