[聚合文章] canvas 四处乱窜的小球

HTML5 1900-01-01 18 阅读
QQ20171227-203915-HD.gif

主要思路:使用面向对象的方法:首先定义一个球的构造函数,在函数原型上写两个方法:
1. 画球的方法;
2. 球移动的方法;
然后,使用for循环实例化多个小球不停更新canvas画布形成小球碰撞的景象
下面是构造函数的参数方法

// 定义一个球的构造函数        function Boll(x,y,r,color,speedx,speedy){            this.x = x;  this.y = y;  this.r = r;  this.color = color;            this.speedx = speedx;   this.speedy = speedy;        }        // 画的方法        Boll.prototype.draw = function(){            context.beginPath();            context.arc(this.x,this.y,this.r,0,Math.PI*2);            context.fillStyle = this.color;            context.fill();        }        // 球的移动方法        Boll.prototype.move = function(){            this.x += this.speedx;            this.y += this.speedy;            // 碰壁检测            if(this.x<this.r || this.x>canvas.width-this.r){                this.speedx *= -1;            }            if(this.y<this.r || this.y>canvas.height-this.r){                this.speedy *= -1;            }        }

封装了两个随机数函数,用来随机小球半径,初始位置的x轴和y轴坐标以及小球的颜色。

// 随机数函数        function randNum(min,max){            return parseInt(Math.random()*(max-min) + min) ;        }// 随机颜色        function randColor(){            return "rgb("+randNum(0,256)+","+randNum(0,256)+","+randNum(0,256)+")";        }

使用for循环实例化100个对象,生成100个颜色,半径,初始位置不同的的小球,在canvas画布里碰壁反弹。

var arr = [];        for(var i = 0 ; i < 100 ;i++){            var r = randNum(5,45);            var x = randNum(r,canvas.width-r);            var y = randNum(r,canvas.height-r);            var speedx = randNum(1,4);            var speedy = randNum(1,4);            var color = randColor();            var newboll = new Boll(x,y,r,color,speedx,speedy);            arr.push(newboll);        }

封装一个act函数使用window.requestAnimationFrame()方法做动画,与setInterval,setTimeout类似。
window.requestAnimationFrame:
概念:采用系统时间间隔,保持最佳绘制效率,不会因为间隔时间过短,造成过度绘制,增加开销;也不会因为间隔时间太长,使用动画卡顿不流畅。
区别:它调取cpu性能(显卡性能),效率高;而setInerval和setTimeout是调取浏览器的性能,有局限性。

function act(){    context.clearRect(0,0,canvas.width,canvas.height);    for(var i = 0 ; i < arr.length ; i++){        arr[i].draw();        arr[i].move();    }    window.requestAnimationFrame(act);}act();

总结:使用面向对象方法定义了一个球的构造函数,好处在于可以在多处调用

注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。