如何仅使用鼠标坐标清除(或取消)画布?

时间:2018-06-13 04:46:40

标签: javascript reactjs html5-canvas

我使用React在客户端鼠标坐标的画布上绘图。

但是,我也尝试使用客户端的鼠标坐标清除现有画布。我怎么能这样做?基本上画布只会在鼠标悬停区域中清除。

最后有没有办法使用context将样式属性添加到此路径?

1 个答案:

答案 0 :(得分:0)

我想到了一些可以帮助您的东西。

<body id="paper" onload="init()">
  <canvas id="canvas" width="200" height="200" style="border: 1px solid #000" onmousedown="deleting=true" onmouseup="deleting=false"></canvas>
</body>
<script type="text/javascript">
    var mouseX = 0, mouseY = 0;
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext('2d');
    var body = document.getElementById("paper");
    var deleting = false;

    function init() {
        window.addEventListener("mousemove", function(e) {
            mouseX = e.pageX - canvas.offsetLeft;
            mouseY = e.pageY - canvas.offsetTop; //this updates the mouse coordinates
        });

        if (typeof mousemove != "undefined") {
            window.addEventListener("mousemove", mousemove);
        }
    }

    function draw() {
        ctx.fillStyle = "#F00";
        ctx.fillRect(0, 0, canvas.width, canvas.height); //red rect filling the canvas
    }
    
    function update() {
        if (deleting) {
            ctx.clearRect(mouseX, mouseY, 10, 10); //10 is our "brush size", you can change that.
        }
    }
    
    update();
    setInterval(update, 10); //JavaScript must keep checking if you're deleting anything. You can decrease the interval for more frequent updating.
    draw();
</script>

如果您正在开发有关绘图的应用程序,这应该使您了解如何制作它。

ctx.fillRect(mouseX, mouseY, 10, 10);是绘图的工作方式。