用html5编写网页版画板程序的示例代码

2023-11-01 14:31:48
183

简单的画板程序,有清空,后退功能。

<!DOCTYPE html>
<html>

<head>
    <title>画板</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>

<body>
    <canvas id="drawing" width="800" height="800"></canvas>
    <br>
    <button onclick="clearCanvas()">Clear</button>
    <button onclick="goBack()">Back</button>
    <script>
        var canvas = document.getElementById("drawing");
        var context = canvas.getContext("2d");
        var painting = false;
        var drawingHistory = [];
        var currentIndex = -1;

        function startPainting(event) {
            painting = true;
            context.beginPath();
            context.moveTo(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop);
            currentIndex++;
            drawingHistory[currentIndex] = [];
            drawingHistory[currentIndex].push({ x: event.clientX, y: event.clientY });
        }

        function continuePainting(event) {
            if (!painting) return;
            context.lineTo(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop);
            context.stroke();
            drawingHistory[currentIndex].push({ x: event.clientX, y: event.clientY });

        }

        function stopPainting(event) {
            painting = false;
        }

        canvas.addEventListener("mousedown", startPainting);
        canvas.addEventListener("mousemove", continuePainting);
        canvas.addEventListener("mouseup", stopPainting);

        function clearCanvas() {
            context.clearRect(0, 0, canvas.width, canvas.height);
            drawingHistory = [];
            currentIndex = -1;
        }

        function goBack() {
            if (currentIndex >= 0) {
                console.log(currentIndex);
                context.beginPath();
                context.moveTo(drawingHistory[currentIndex][0].x - canvas.offsetLeft, drawingHistory[currentIndex][0].y - canvas.offsetTop);
                for (var i = 0; i < drawingHistory[currentIndex].length; i++) {
                    context.lineTo(drawingHistory[currentIndex][i].x - canvas.offsetLeft, drawingHistory[currentIndex][i].y - canvas.offsetTop);
                    context.stroke();
                    context.globalCompositeOperation = "destination-out";
                    context.stroke();
                }
                context.globalCompositeOperation = "source-over";
                drawingHistory[currentIndex] = [];
                currentIndex--;
            }
        }  
    </script>
</body>

</html>