程序猿首页投稿(暂停使用,暂停投稿)程序员

内裤总动员之程序猿的小动画--躁动的小球

2016-05-23  本文已影响379人  5034af144007

躁动的小球

各位观众老爷大家好,欢迎收看内裤总动员之程序猿的小动画--躁动的小球. 在这里首先说明一下我们的目的:  用canvas制作出500个随机颜色.随机大小.随机位置.速度也是随机的小球在当前的画布内进行移动.


<canvas id='canvas' width='500' height ='500'></canvas>

1.创建canvas标签   并给其 css样式  

#canvas{

box-shaw: 0 0 50px gray;

margin: 100px;

}


2.下面开始写js代码, 我们用构造函数来进行编写.首先需要获取元素.

<script type=''text/javascript">

var canvas = document.getElementById("canvas");

var ctx = canvas.getContext("2d");

</script>

3. 获取canvas画布的kuangao

var canvaswidth = canvas.width;

var canvasheight = canvas.height;

4.创建随机数. 他将用来 我们的各种属性的随机数的调用. max代表最大数 min代表最小数

function suiji(min,max){

return parseInt(Math.random() * (max-min+1) + min );

}

5.创建随机的颜色函数  他将用来圆的颜色随机

function suijicolor(){

return "rgba("+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+(Math.random()+0.1)+")";

}

6.创建构造函数  x代表left,y代表top,r代表半径,color代表颜色,speedx代表速度x,speedy代表速度y

function Qiu(x,y,r,color,speedx,speedy){

this. r = r || suiji(10,30);

this.x = x || suiji( this.r , canvaswidth - this.r );

this.y =  y || suiji( this.r , canvasheight - this . r  );

this. color = color || suijicolor();

this.speedx = speedx || suiji(3, 5);

this.speedy = speedy || suiji(3,5);

//在这里我在构造函数里写图形的绘制.

this.huizhi = function (){

  ctx.beginPath();

  ctx.fillstyle = this.color;

  ctx.arc = (this.x,this.y,this.r,0, Math.PI * 2, true):

  ctx.fill();

 }

//图形绘制后 将写出圆的小球动画的限制

 this. donghua = function(){

  this.x  += this.speedx;

   this.y  += this.speedy;

   if( this.x <= this.r || this.x >= canvaswidth - this.r ){

      this.speedx *=  -1;

    }else if( this.y <= this.r ||  this.y >= canvasheight - this.r){

         this.speedy *= -1;

    }

     this.huizhi();

  }

}

//创建500个小球.

var arrays =[];

for(var i =0 ; i < 500; i++){

   var qiu = new Qiu();

   qiu.huizhi();

   arrays.push(qiu);

}

//链接动画,让小球动起来

setInterval(function(){ 

ctx.clearRect(0,0,canvaswidth,canvasheight);

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

     arrays[i].donghua();

  }

},16);


  躁动的小球

好啦,感谢各位观众老爷的赏脸,内裤感激不尽,如有更好的办法不妨赐教,谢谢大家. 我还会写一些其他的东西和知识点分享给大家.

上一篇下一篇

猜你喜欢

热点阅读