使用Canvas绘制星星闪烁的效果

html-css011

使用Canvas绘制星星闪烁的效果,第1张

如图所示,当鼠标移上canvas区域的时候,显示星星闪烁的效果,星星本身还会有一个缓慢飘动的速度,当星星飘出canvas区域的时候,该星星消失,canvas区域的某个地方又会重生一个星星。

首先准备两张图片:

背景图:girl.jpg

星星的序列帧图片:star.png

js库:commonFunctions.js

项目主文件:index.html

文件目录如下:

使用内框架的结构,加入IFRAME

<iframe height=100% width=100% src="http://www.gbtags.com/gb/rtwidget-replayerpreview/1050.htm" frameborder=0 allowfullscreen></iframe>

首先是要绘制星星,在flash中有绘制星形的工具,那么用代码是怎么实现呢?星形实则是规则的凸多边形。因为是规则的画的时候只要依次算出凹点的坐标和凸点的坐标,就可以画出星形了。代码如下:

package 

{

import flash.display.Shape

import flash.events.Event

public class star extends Shape

{

private var alp:Number = 0//透明度变化量

public var speed:int = Math.random ()*10+10//随机速度

//参数分别是:小半径,大半径,边数,填充色,透明值,弧度

public function star(r:Number ,R:Number ,n:int ,fillcolor:uint ,alp:Number ,a:Number =0)

{

this.graphics.moveTo(r,0)

//开始填充

this.graphics.beginFill(fillcolor,alp)

for (var i:Number =0 i<n i++)

{

a +=  Math.PI / n

this.graphics.lineTo(R*Math.cos (a),R*Math.sin(a))

a +=  Math.PI / n

this.graphics.lineTo(r*Math.cos (a),r*Math.sin(a))

}

}

}

}

下面我们再来补上闪烁的代码:

package 

{

import flash.display.Shape

import flash.events.Event

public class star extends Shape

{

private var alp:Number = 0//透明度变化量

public var speed:int = Math.random ()*10+10//随机速度

//参数分别是:小半径,大半径,边数,填充色,透明值,弧度

public function star(r:Number ,R:Number ,n:int ,fillcolor:uint ,alp:Number ,a:Number =0)

{

this.graphics.moveTo(r,0)

//开始填充

this.graphics.beginFill(fillcolor,alp)

for (var i:Number =0 i<n i++)

{

a +=  Math.PI / n

this.graphics.lineTo(R*Math.cos (a),R*Math.sin(a))

a +=  Math.PI / n

this.graphics.lineTo(r*Math.cos (a),r*Math.sin(a))

}

this.addEventListener(Event.ENTER_FRAME,loopAlp)

}

private function loopAlp(e:Event ):void

{

this.rotation +=  Math.random() * 20 - 10

if (this.alpha > 0.9)

{

alp = 0

}

else if (this.alpha <=0.0)

{

alp = 1

}

this.alpha +=  (alp - this.alpha) / speed//渐变透明度(代码实现淡入淡出的一种方法)

//trace(sta.alpha )

}

}

}

上面的2个实例是actionscript3.0类文档,保存名为:star.这个类做好了,在flash中运用也是非常简单的,新建一个actionscript3.0文件,给它绑定一个名为:flie.的类文档(别告诉我你不会!真的不会?再问!)。在文档中输入代码:

package 

{

import flash.display.Sprite

public class flie extends Sprite

{

public function flie()

{

for (var i:int=0 i<17 i++)

{

var r:Number = Math.random() * 1 + 2

var R:Number = Math.random() * 4 + 7

var n:Number = Math.floor(Math.random() * 9) + 4

var u:uint = Math.floor(Math.random() * 0xffffff) | 0xcccccc

var al:Number = Math.random() * 1.5 + 0.5

var sta:star = new star(r,R,n,u,al)

sta.x = Math.random() * stage.stageWidth

sta.y = Math.random() * stage.stageHeight / 2

addChild(sta)

}

}

}

}

全部保存,测试影片,这是你想要的效果吗?

a,太复杂了,我看不懂,能解释一下代码含义吗?

b,我对as3.0不感兴趣!

c,这更本不是我想要看的的效果,答非所问!