码迷,mamicode.com
首页 > 其他好文 > 详细

canvas弹跳球----源码分享与知识点总结

时间:2017-07-06 22:48:26      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:执行   over   pat   flow   text   getc   随机   sha   anim   

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);

 

canvas弹跳球----源码分享与知识点总结

标签:执行   over   pat   flow   text   getc   随机   sha   anim   

原文地址:http://www.cnblogs.com/Nirvana-zsy/p/7128491.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!