js实现电子白板

功能:使用画笔绘制笔迹(线条)、橡皮檫

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>js实现电子白板</title>
</head>
<body>
    <canvas id="canvas" width="500px" height="500px" style="border: 3px solid black;"></canvas>
    <br>
    <button onclick="show()">显示</button>
    <button onclick="hide()">隐藏</button>
    <button onclick="clearAnnote()">清空</button>
    <button id="xiangpicha" onclick="xiangpicha()">橡皮檫</button>
    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        var state_bi = true;
        var state_press = false;
        var lastX, lastY;
        var state_xiangpicha = false;

        function show(){
            canvas.style.display = "block";
            state_bi = true;
        }
        function hide(){
            canvas.style.display = "none";
            state_bi = false;
        }

        function clearAnnote(){
            ctx.clearRect(0,0,canvas.width, canvas.height);
        }

        function xiangpicha(){
            state_xiangpicha = state_xiangpicha == true ? false : true;
            if(state_xiangpicha){
                document.getElementById("xiangpicha").innerText = "关闭橡皮檫";
                state_bi = false;
            }else{
                document.getElementById("xiangpicha").innerText = "橡皮檫";
                state_bi = true;
            }
        }

        canvas.addEventListener("mousedown", (e)=>{
            state_press = true;

            if(state_bi){
                [lastX, lastY] = [e.offsetX, e.offsetY];
            }

            if(state_xiangpicha){
                ctx.clearRect(e.offsetX - 3, e.offsetY - 3, 6, 6);
            }
        })

        canvas.addEventListener("mousemove", (e)=>{
            if(state_bi && state_press){
                drawLine(lastX, lastY, e.offsetX, e.offsetY);
                [lastX, lastY] = [e.offsetX, e.offsetY];
            }

            if(state_xiangpicha && state_press){
                ctx.clearRect(e.offsetX - 3, e.offsetY - 3, 6, 6);
            }
        })

        canvas.addEventListener("mouseup", (e)=>{
            state_press = false;
        })

        function drawLine(x1, y1, x2, y2){
            ctx.beginPath();
            ctx.moveTo(x1, y1);
            ctx.lineTo(x2, y2);
            ctx.lineWidth = 3;
            ctx.strokeStyle = "#FF0000";
            ctx.stroke();
        }
    </script>
</body>
</html>

 

posted @ 2023-10-09 14:39  十一的杂文录  阅读(69)  评论(0编辑  收藏  举报