1、了解canvas
这是画布
2、设置body背景色
3、
初始化画布及context
4、定义星星对象
<
canvas
id
=
"stars"
height
=
"600"
>
</
canvas
>
2、设置body背景色
<
style
type
=
"text/css"
>
body
{
background-color:
black;
}
</
style
>
context作为全局变量
var
context
;
function
init
(
)
{
//获取canvas
var
stars
=
document
.
getElementById
(
"stars"
)
;
windowWidth
=
window
.
innerWidth
;
stars
.
width
=
windowWidth
;
//获取context
context
=
stars
.
getContext
(
"2d"
)
;
}
4、定义星星对象
//星星对象
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"
;