html5画布里随机显示圆,HTML5 Canvas随机圆周运动

圆周运动的原理

4e5f691474c7

圆周运动1.PNG

如上图所示,其实圆周运动,就是通过运动的角度deg来求出物体在x轴和y轴上运动的偏移量,分别为radius*Math.cos(deg)和radius*Math.sin(deg)。

了解了上述原理之后,就可以开始写一个随机圆周运动的DEMO,效果图如下

4e5f691474c7

圆周运动.PNG

基本的设计思路

*利用面向对象的思想创建一个圆模型对象。

*再创建一个帧动画模型。

*创建实例,执行动画。

创建圆模型对象

将画圆形的x,y坐标、半径、初始角度、颜色、宽度等要素,封装在圆模型这个对象的构造函数里面,然后通过给原型添加方法,一个是draw画圆形的方法和move圆形运动的方法,让所有圆形的实例共享这些方法,还有自己相应的属性,这里用到了,构造函数模式和原型模式创建对象的方法思想。

var Square = function(x,y,radiu,option){

this.wid = canvas.width;

this.hei = canvas.height;

this.ctx = ctx;

this.x = x;

this.y = y;

this.radiu = radiu;

this.option = option;

this.radius = Math.random()*5 + 1;

this.angle = 0;//圆周运动的初始角度

};

Square.prototype = {

draw:function(){

this.ctx.beginPath();

this.ctx.strokeStyle = this.option.strokeStyle;

this.ctx.lineWidth = this.option.lineWidth;

this.ctx.arc(this.x,this.y,this.radiu,0,2*Math.PI,true);

this.ctx.stroke();

},

move:function(){

/*根据角度计算出x轴和y轴的偏移量*/

this.x += this.radius*Math.cos(this.angle*(Math.PI/180));

this.y += this.radius*Math.sin(this.angle*(Math.PI/180));

this.angle+=5;//角度每次递增5个像素

this.draw();

}

};

创建帧动画对象

同样的道理创建帧动画对象,并且增加一个存放圆实例的数组,每实例化一个圆形,就将它存到数组中,然后每次render渲染之前,都先把之前的画布清除掉,然后执行start方法循环地渲染画布,达到动画的效果。

var Far = function(){

this.width = canvas.width;

this.height = canvas.height;

this.ctx = ctx;

this.timer = null;

this.squares = [];//创建数组,用于存放圆实例

};

Far.prototype = {

//循环渲染

start : function(){

this.timer = setInterval((function(param){

return function(){param.render();}

})(this),30);

},

//渲染方法

render : function(){

/*将之前的画布清除掉*/

this.ctx.clearRect(0,0,canvas.width,canvas.height);

/*遍历每个圆实例,让这些圆角度发生变化,从而让运动轨迹发送变化*/

for(i in this.squares){

this.squares[i].move();

/*圆角度增加判断*/

if(this.squares[i].angle>360){

this.squares[i].angle = 0;

}

}

}

};

最后创建实例完成动画效果

/*创建帧实例*/

var frame = new Far();

/*创建圆实例*/

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

/*圆的所有属性都是一定范围内的随机数*/

var x = Math.random()*(canvas.width);

var y = Math.random()*(canvas.height);

var radiu = Math.random()*20;

var r = Math.floor(Math.random()*256);

var g = Math.floor(Math.random()*256);

var b = Math.floor(Math.random()*256);

var a = Math.random();

var option = {

strokeStyle : 'rgba('+r+','+g+','+b+','+a+')',

lineWidth : Math.random()*10

};

//把圆实例放到帧模型的数组中

frame.squares[i] = new Square(x,y,radiu,option);

}

//开始渲染

frame.start();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值