html+js手写一个画板

425 阅读1分钟
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        canvas {
            display: block;
        }
    </style>
</head>

<body>

    <canvas width="500" height="400"></canvas>
    <div class="wrapper">
        <input id="color" type="color" value="#ffffff">
        <input id="range" type="range" max="50" min="5">
        <button id="brush" type="button">画笔</button>
        <button id="rubbish" type="button">垃圾桶</button>
        <button id="save" type="button">保存</button>
    </div>


    <script>
        function $(selector) {
            return typeof selector === "string" ? document.querySelector(selector) : selector;
        };

        var canvas = document.querySelector("canvas"),
            ctx = canvas.getContext("2d");

        ctx.fillRect(0, 0, canvas.width, canvas.height);
        bindEventFn();

        function bindEventFn() {
            $("#brush").addEventListener("click", brushFn);
            $("#rubbish").addEventListener("click", rubshFn);
            $("#save").addEventListener("click", saveFn);
            canvas.addEventListener("mousedown", startFn)
        };

        //1.source-over
        //这是默认值,他表示绘制的图形将画在现有画布之上
        //2.destination-out
        //在与源不重叠的区域上保留目标。其他部分都变成透明的。

        function brushFn() {
            if (this.innerHTML === "画笔") {
                this.innerHTML = "橡皮擦";
                ctx.globalCompositeOperation = "source-over";
            } else {
                this.innerHTML = "画笔";
                ctx.globalCompositeOperation = "destination-out";
            }
        }


        function saveFn() {
            //把画布转换为路径
            var src = canvas.toDataURL();
            var img = new Image(); //创建一张图片
            img.src = src;
            img.onload = function() {
                document.body.appendChild(img);
            }

        }


        function rubshFn() {
            ctx.fillRect(0, 0, canvas.width, canvas.height);
        }

        var startPos = null;

        function startFn(e) {
            startPos = {
                x: e.pageX - this.offsetLeft,
                y: e.pageY - this.offsetTop
            };
            ctx.beginPath();
            ctx.moveTo(startPos.x, startPos.y)
            canvas.addEventListener("mousemove", moveFn);
            canvas.addEventListener("mouseup", upFn);
        };

        function moveFn(e) {
            var moveX = e.pageX - this.offsetLeft,
                moveY = e.pageY - this.offsetTop;

            ctx.lineWidth = $("#range").value;
            ctx.strokeStyle = $("#color").value;
            ctx.lineTo(moveX, moveY);
            ctx.stroke();
        };

        function upFn() {
            canvas.removeEventListener("mousemove", moveFn);
        }
    </script>
</body>

</html>