【JavaScript】满天星

参考:

1、http://www.w3school.com.cn/tags/canvas_filltext.asp

2、产生随机数:http://www.cnblogs.com/banbu/archive/2012/07/25/2607880.html

效果图:

 

思路:

1、创建一个画布。(背景为黑色)

2、绘制1个“星星”,设法变成n个。

3、把画布放入HTML页面中。

代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title></title>
    <style type="text/css">
        canvas {
            background-color: black;
        }
    </style>
</head>
    <body>
        <canvas id="myCanvas" width="1024" height="768" style="border:1px solid #d3d3d3;">
         </canvas>
        <script>
            var c = document.getElementById("myCanvas");
            var ctx = c.getContext("2d");

            ctx.font = "30px Verdana";
            // Create gradient
            var gradient = ctx.createLinearGradient(0, 0, c.width, 0);
            gradient.addColorStop("0", "magenta");
            gradient.addColorStop("0.5", "blue");
            gradient.addColorStop("1.0", "red");
            // Fill with gradient
            ctx.fillStyle = gradient;
            for (i = 1; i < 300; ++i) {
                ctx.fillText("*", Math.random()*1024, Math.random()*768);
            }
        </script>
</body>

</html>

重用w3school代码。

 

posted @ 2017-04-21 21:34  xkfx  阅读(726)  评论(0编辑  收藏  举报