用canvas制作简单的画笔

543 阅读1分钟
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    </style>
</head>
<body>
<canvas></canvas>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.20/lodash.js"></script>
<script>
    const canvas = document.querySelector("canvas");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    let preX = 0;
    let preY = 0;
    const ctx = canvas.getContext("2d");

    function moveFn(e) {
        e = e || event;
        const x = e.pageX;
        const y = e.pageY;
        ctx.moveTo(preX, preY);
        ctx.lineTo(x, y);
        ctx.strokeStyle = "red";
        ctx.stroke();
        preX = x;
        preY = y;
    }
    const throttleMoveFn = _.throttle(moveFn, 50);
    window.addEventListener("mousedown", function (e) {
        e = e || event;
        preX = e.pageX;
        preY = e.pageY;
        window.addEventListener("mousemove", throttleMoveFn);
    });
    window.addEventListener("mouseup", function () {
        window.removeEventListener("mousemove", throttleMoveFn);
    });
</script>
</html>
```
```