用canvas畫七彩虹傘

2020-09-22 11:01:13

彩虹小傘效果圖如下:
彩虹小傘效果圖
程式碼如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>作業1</title>
    <style>
        #canvas {
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: 100px auto;
        }
    </style>
</head>

<body>
    <canvas id="canvas" width="500" height="800"></canvas>
    <script>
        var canvas = document.getElementById("canvas");
        var pen = canvas.getContext("2d");
        // 彩虹七色小傘
        var rainbow = ["#FF0000","#FF7F00","#FFFF00","#00FF00","#00FFFF","#0000FF","#871F78"]
        for (var i = 0; i < 7; i++) {
            pen.fillStyle = pen.strokeStyle = rainbow[i];
            // 傘蓋
            pen.beginPath();
            pen.arc(30 + 70 * i, 140, 30, Math.PI, 2 * Math.PI);
            pen.closePath();
            pen.fill();
            // 傘柄
            pen.beginPath();
            pen.moveTo(30 + 70 * i, 140);
            pen.lineTo(30 + 70 * i, 187);
            pen.closePath();
            pen.stroke();
            // 傘把
            pen.beginPath();
            pen.arc(26 + 70 * i, 187, 4, 0, Math.PI);
            pen.stroke();
        }
        // 隨機變顏色的七個小傘
        // setInterval(function () {
        //     for (var i = 0; i < 7; i++) {
        //         pen.fillStyle = pen.strokeStyle = randomColor();
        //         // 傘蓋
        //         pen.beginPath();
        //         pen.arc(30 + 70 * i, 40, 30, Math.PI, 2 * Math.PI);
        //         pen.closePath();
        //         pen.fill();
        //         // 傘柄
        //         pen.beginPath();
        //         pen.moveTo(30 + 70 * i, 40);
        //         pen.lineTo(30 + 70 * i, 87);
        //         pen.closePath();
        //         pen.stroke();
        //         // 傘把
        //         pen.beginPath();
        //         pen.arc(26 + 70 * i, 87, 4, 0, Math.PI);
        //         pen.stroke();
        //     }
        // }, 1000)

        // 生成隨機顏色的方法
        function randomColor() {
            var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f']
            var c = ''
            for (var i = 0; i < 6; i++) {
                c += arr[Math.round(Math.random() * 15)]
            }
            return "#" + c;
        }
    </script>
</body>

</html>