canvas 满天星

本文介绍了一个使用HTML5 Canvas和JavaScript绘制满天星与月亮的简单教程。通过设置画布尺寸,填充背景,随机绘制星星,并添加月亮元素,实现了浪漫的夜空效果。此外,还介绍了如何加载并显示图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

<script type="text/javascript" src="jquery-2.2.0.min.js"></script>

<canvas id="canvas" width="750" height="1134"></canvas>

<script>

    //绘制满天星
    function draw(id) {

        var canvas = document.getElementById(id);
        var context = canvas.getContext('2d');
        context.fillStyle = "#000";
        //context.strokeStyle = "#f60";
        //context.lineWidth = 5;
        context.fillRect(0, 0, 750, 1134);

        //context.fillStyle = "#fff";
        //context.fillText("fillText", 0, 0);

        //********************************** 星星
        context.font = "bold 14px Arial";
        context.textAlign = "left";
        context.textBaseline = "top";
        //context.strokeStyle = "red";

        context.fillStyle = "#fff";
        //context.fillText("*", 0, 0);

        //for (var i = 0; i < 300; i++) {

        //               g.drawString("*", (int) (Math.random() * 1024),

        //                               (int) (Math.random() * 768));

        //}

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

            context.fillText("*", Math.random() * 750,

                            Math.random() * 1134);

        }

        //********************************* 月亮
        //g.fillOval(800, 100, 100, 100);

        //g.setColor(Color.BLACK);

        //g.fillOval(780, 80, 100, 100);
        context.beginPath();

        context.arc(400, 100, 50, 0, 2 * Math.PI, true);
        context.closePath();
        context.fillStyle = '#f6ee74';
        context.fill();

        context.beginPath();

        context.arc(380, 80, 50, 0, 2 * Math.PI, true);
        context.closePath();
        context.fillStyle = "#000";
        context.fill();

        //********************************* 加载图片
        var beauty = new Image();
        beauty.src = "1.png";
        beauty.onload = function () //确保图片已经加载完毕
        {

            context.drawImage(beauty, 100, 100, 400, 600);
        }

    }

    $(function () {
        draw("canvas");

        var canvas = document.getElementById("canvas");
        canvas.onclick = function () {
            var context = canvas.getContext('2d');
            context.font = "bold 14px Arial";
            context.textAlign = "left";
            context.textBaseline = "top";
            context.fillStyle = "#fff";
            for (var i = 0; i < 300; i++) {

                context.fillText("*", Math.random() * 750,

                                Math.random() * 1134);

            }
        };

    });
</script>

 

转载于:https://www.cnblogs.com/frog2008/p/5191614.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值