CanvasJS绘制星空

65 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CanvasJS绘制星星</title>
</head>
<style>
</style>
<body>
<!--PS:目前不知道出了什么问题,只能显示300*150的范围图形-->
    <canvas id="canvas"></canvas>
    <script>
        let canvas = document.getElementById("canvas")
        let ctx = canvas.getContext("2d")
        //黑色背景
        ctx.fillRect(0,0,600,600)
        ctx.translate(300,300)

        //圆形裁剪区域
        ctx.beginPath()
        ctx.arc(0,0,250,0,Math.PI*2,true)
        ctx.clip()

        //渐变蓝色背景
        let linGrad = ctx.createLinearGradient(0,0,600,600)
        linGrad.addColorStop(0,"#232256")
        linGrad.addColorStop(1,"#143778")
        
        //填充颜色
        ctx.fillStyle = linGrad
        ctx.fillRect(-300,-300,600,600)

        //画星星
        for(let j = 1;j<100;j++){
            ctx.save()
            ctx.fillStyle = "#fff"
            ctx.translate(
                250-Math.floor(Math.random()*500),
                250-Math.floor(Math.random()*500)
            )
            drawStar(ctx,Math.floor(Math.random()*4)+2)
            ctx.restore()
        }

        function drawStar(ctx,r){
            ctx.save()
            ctx.beginPath()
            ctx.moveTo(r,0)
            for(let i = 0;i<9;i++){
                ctx.rotate(Math.PI/5)
                if(i%2 == 0){
                    ctx.lineTo((r/0.525731)*0.200811,0)
                }else{
                    ctx.lineTo(r,0)
                }
            }
            ctx.closePath()
            ctx.fill()
            ctx.restore()
        }
    </script>
</body>
</html>