<!DOCTYPE html>
<
html
>
<
head
>
<
meta
charset
=
"utf-8"
>
<
title
>
满
天
繁
星
</
title
>
<
script
>
var
arr
=
new
Array
(
)
;
var
starCount
=
1000
;
var
context
;
//初始化画布及context
function
init
(
)
{
//获取canvas
var
stars
=
document
.
getElementById
(
"stars"
)
;
windowWidth
=
window
.
innerWidth
;
stars
.
width
=
windowWidth
;
//获取context
context
=
stars
.
getContext
(
"2d"
)
;
}
//星星对象
var
Star
=
function
(
)
{
this
.
x
=
-1
;
//横坐标
this
.
y
=
-1
;
//纵坐标
this
.
text
=
"*"
;
//文本
this
.
font
=
"italic bold 24px serif"
;
this
.
color
=
"white"
;
//颜色
//产生坐标
this
.
getPos
=
function
(
)
{
var
xx
=
windowWidth
*
Math
.
random
(
)
;
var
yy
=
600
*
Math
.
random
(
)
;
this
.
x
=
Math
.
floor
(
xx
)
;
this
.
y
=
Math
.
floor
(
yy
)
;
}
//产生随机颜色
this
.
getColor
=
function
(
)
{
var
_r
=
Math
.
random
(
)
;
if
(
_r
<
0.2
)
{
this
.
color
=
"#0000FF"
;
}
else
if
(
_r
<
0.5
)
{
this
.
color
=
"white"
;
}
else
if
(
_r
<
0.8
)
{
this
.
color
=
"#989898"
;
}
else
{
this
.
color
=
"#B8B8B8"
;
}
}
//产生随机fontSize
this
.
getFont
=
function
(
)
{
var
_r
=
Math
.
random
(
)
*
12+3
;
this
.
font
=
"italic bold "
+
Math
.
ceil
(
_r
)
+
"px serif"
;
}
//初始化
this
.
init
=
function
(
)
{
this
.
getPos
(
)
;
this
.
getColor
(
)
;
this
.
getFont
(
)
;
}
//绘制
this
.
draw
=
function
(
)
{
context
.
fillStyle
=
this
.
color
;
context
.
font
=
this
.
font
;
context
.
fillText
(
this
.
text
,
this
.
x
,
this
.
y
)
;
}
}
window
.
onload
=
function
(
)
{
init
(
)
;
//画星星
for
(
var
i
=
0
;
i
<
starCount
;
i
++
)
{
var
star
=
new
Star
(
)
;
star
.
init
(
)
;
star
.
draw
(
)
;
arr
.
push
(
star
)
;
}
drawMoon
(
)
;
playStars
(
)
;
}
//画月亮
function
drawMoon
(
)
{
var moon = new Image();
moon.src = "../img/moon.png"
context.drawImage(moon,10,10);
}
//星星闪起来
function
playStars
(
)
{
for
(
var
n
=
0
;
n
<
starCount
;
n
++
)
{
arr
[
n
]
.
getColor
(
)
;
arr
[
n
]
.
draw
(
)
;
}
setTimeout
(
"playStars()"
,
500
)
;
}
</
script
>
<
style
type
=
"text/css"
>
body
{
background-color:
black;
}
</
style
>
</
head
>
<
body
>
<
canvas
id
=
"stars"
height
=
"600"
>
</
canvas
>
</
body
>
</
html
>