劉任昌chatgpt寫出計算機

劉任昌Canvas 計算機

以上用chatgpt產生的程式碼

    <title>劉任昌Canvas 計算機</title>
    <style>
    canvas { border: 1px solid #000;  }
    </style>

      <H1>劉任昌Canvas 計算機</H1>
    <canvas id="calculatorCanvas" width="320" height="480"></canvas>

    <script>
        const canvas = document.getElementById("calculatorCanvas");
        const ctx = canvas.getContext("2d");
        let currentInput = "";
        let result = "";

        const buttons = [
            ["7", "8", "9", "/"],
            ["4", "5", "6", "*"],
            ["1", "2", "3", "-"],
            ["0", ".", "=", "+"],
            ["C"]
        ];

        function drawCalculator() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = "#fff";
            ctx.fillRect(0, 0, 320, 480);
            ctx.fillStyle = "#000";
            ctx.font = "30px Arial";
            ctx.fillText(currentInput || result || "0", 10, 50);

            buttons.forEach((row, rowIndex) => {
                row.forEach((text, colIndex) => {
                    const x = colIndex * 80;
                    const y = 100 + rowIndex * 80;
                    ctx.fillStyle = "#ddd";
                    ctx.fillRect(x, y, 80, 80);
                    ctx.strokeRect(x, y, 80, 80);
                    ctx.fillStyle = "#000";
                    ctx.fillText(text, x + 30, y + 50);
                });
            });
        }

        canvas.addEventListener("click", (e) => {
            const rect = canvas.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;

            buttons.forEach((row, rowIndex) => {
                row.forEach((text, colIndex) => {
                    const btnX = colIndex * 80;
                    const btnY = 100 + rowIndex * 80;
                    if (x > btnX && x < btnX + 80 && y > btnY && y < btnY + 80) {
                        handleInput(text);
                    }
                });
            });
        });

        function handleInput(input) {
            if (input === "C") {
                currentInput = "";
                result = "";
            } else if (input === "=") {
                try {
                    result = eval(currentInput).toString();
                } catch (e) {
                    result = "錯誤";
                }
                currentInput = "";
            } else {
                currentInput += input;
            }
            drawCalculator();
        }

        drawCalculator();
    </script>

留言

這個網誌中的熱門文章

20241028.CANVAS

劉任昌學習Bro Code製作計算機

劉任昌STYLE,SCRIPT在HTML之後