躁動的小球
各位觀眾老爺大家好,歡迎收看內(nèi)褲總動員之程序猿的小動畫--躁動的小球. 在這里首先說明一下我們的目的:? 用canvas制作出500個隨機(jī)顏色.隨機(jī)大小.隨機(jī)位置.速度也是隨機(jī)的小球在當(dāng)前的畫布內(nèi)進(jìn)行移動.
<canvas id='canvas' width='500' height ='500'></canvas>
1.創(chuàng)建canvas標(biāo)簽?? 并給其 css樣式??
#canvas{
box-shaw: 0 0 50px gray;
margin: 100px;
}
2.下面開始寫js代碼, 我們用構(gòu)造函數(shù)來進(jìn)行編寫.首先需要獲取元素.
<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.創(chuàng)建隨機(jī)數(shù). 他將用來 我們的各種屬性的隨機(jī)數(shù)的調(diào)用. max代表最大數(shù) min代表最小數(shù)
function suiji(min,max){
return parseInt(Math.random() * (max-min+1) + min );
}
5.創(chuàng)建隨機(jī)的顏色函數(shù)? 他將用來圓的顏色隨機(jī)
function suijicolor(){
return "rgba("+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+(Math.random()+0.1)+")";
}
6.創(chuàng)建構(gòu)造函數(shù)? 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);
//在這里我在構(gòu)造函數(shù)里寫圖形的繪制.
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();
? }
}
//創(chuàng)建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);
好啦,感謝各位觀眾老爺?shù)馁p臉,內(nèi)褲感激不盡,如有更好的辦法不妨賜教,謝謝大家. 我還會寫一些其他的東西和知識點分享給大家.