您的位置:首页 > 其它

【实践】canvas弹跳球----源码分享与知识点总结

2017-07-06 21:43 197 查看
html部分

<h1>bouncing balls</h1>
<canvas></canvas>


css部分

html, body {
margin: 0;
}
body {
overflow: hidden;//
height: inherit;//这两句很重要,是宽高100%的重要因素之一
}
h1 {
font-size: 2rem;
letter-spacing: -1px;
position: absolute;
margin: 0;
top: -4px;
right: 5px;
color: transparent;
text-shadow: 0 0 4px white;
}


js部分:

var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var width = canvas.width = window.innerWidth;
var height = canvas.height = window.innerHeight;//这两句也是宽高100%的重要因素之一
var balls=[];

// 随机数函数
function random(min,max) {
var num = Math.floor(Math.random()*(max-min)) + min;
return num;
}

//Ball构造器
function Ball(x,y,vX,vY,color,size){
this.x=x;
this.y=y;
this.vX=vX;
this.vY=vY;
this.color=color;
this.size=size;
}
Ball.prototype.init=function(){
ctx.beginPath();
ctx.fillStyle=this.color;
ctx.arc(this.x,this.y,this.size,0,2*Math.PI);
ctx.fill();
}
Ball.prototype.update=function(){
if(this.x+this.size>=width||this.x-this.size<=0){
this.vX=-this.vX;
this.color='rgb('+random(0,255)+','+random(0,255)+','+random(0,255)+')';
}
if(this.y+this.size>=height||this.y-this.size<=0){
this.vY=-this.vY;
this.color='rgb('+random(0,255)+','+random(0,255)+','+random(0,255)+')';
}
this.x+=this.vX;
this.y+=this.vY;
}

//用来循环调用的函数
function fool(){
//这两句很重要!!!!!
//每次调用这个函数就重新对整个canvas容器填充一次,不然上一帧留下的球是不会消失的
//而且rgba最后一个透明度用0.25效果超级好!
//每次覆盖涂色透明度0.25,不会把上一帧的图完全覆盖,4个帧之内有一种渐变得效果
ctx.fillStyle = 'rgba(0, 0, 0, 0.25)';
ctx.fillRect(0, 0, width, height);

//产生随机参数小球
while(balls.length<30){
var ball=new Ball(random(20,width-20),
random(20,height-20),
random(-10,10),
random(-10,10),
'rgb('+random(0,255)+','+random(0,255)+','+random(0,255)+')',
random(10,20));
balls.push(ball);
}

//对所有小球执行函数
for(var i=0;i<balls.length;i++){
balls[i].init();
balls[i].update();
}
// requestAnimationFrame(fool());//这个是比setInterval()性能更好的一种解决方案,但是兼容性还不够好
}

setInterval("fool()",20);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: