在画布上用圆圈擦除以查看z-index

时间:2015-11-19 13:21:42

标签: javascript html5 canvas

我正在尝试创建一个分层绘图应用程序(带有背后某些东西的画布),我想要擦除并浏览z-index顶部的画布。但由于某种原因,我不能继续下去。

我认为在draw方法中处理画布的方式有问题,但我不确定。

以下代码将画布放在另一个画布的顶部,其中上部为蓝色,下部为红色,目的是在鼠标移动时在上部蓝色画布上以圆形形状擦除,以便擦除带有鼠标的画布,就像Photoshop或GIMP中的橡皮擦一样。

<html>
<script type="text/javascript">
//inspired by http://stackoverflow.com/questions/2368784/draw-on-html5-canvas-using-a-mouse
var canvas, canvasUnder, ctx, ctxUnder, circle, drawing = false,
    prevX = 0,
    currX = 0,
    prevY = 0,
    currY = 0;

var x = "black",
    y = 2;

var w,h;

function init() {
    canvas = document.getElementById('can');
    ctx = canvas.getContext("2d");

    canvasUnder = document.getElementById('under');
    ctxUnder = canvasUnder.getContext("2d");

    w = canvas.width;
    h = canvas.height;
    canvas.addEventListener("mousemove", function (e) {
        findxy('move', e)
    }, false);
    canvas.addEventListener("mousedown", function (e) {
        findxy('down', e)
    }, false);
    canvas.addEventListener("mouseup", function (e) {
        findxy('up', e)
    }, false);
    canvas.addEventListener("mouseout", function (e) {
        findxy('out', e)
    }, false);

    ctx.rect(0,0,canvas.width,canvas.height);
    ctx.fillStyle="blue";
    ctx.fill();

    //fill the canvas under with solid color to start with
    ctxUnder.rect(0,0,canvasUnder.width,canvasUnder.height);
    ctxUnder.fillStyle="red";
    ctxUnder.fill();
}

function draw() {
    circle = new Path2D();
    circle.arc(currX,currY,16,0,2*Math.PI);
    ctx.clip(circle);
    ctx.clearRect(0, 0, w, h);
    ctx.restore();
}

function findxy(res, e) {
    if (res == 'down') {
        prevX = currX;
        prevY = currY;
        currX = e.clientX - canvas.offsetLeft;
        currY = e.clientY - canvas.offsetTop;

        drawing = true;
    }
    if (res == 'up' || res == "out") {
        drawing = false;
    }
    if (res == 'move') {
        if (drawing) {
            prevX = currX;
            prevY = currY;
            currX = e.clientX - canvas.offsetLeft;
            currY = e.clientY - canvas.offsetTop;
            draw();
        }
    }
}
</script>
<body onload="init()">
    <canvas id="under" width="400" height="400" style="position:absolute;top:10%;left:10%;border:2px solid;" z-index="1;"></canvas>
    <canvas id="can" width="400" height="400" style="position:absolute;top:10%;left:10%;border:2px solid;" z-index="2;"></canvas>
</body>
</html>

问题是:为什么它只适用于第一次调用draw()而不是之后?

我在这里设置了一个小提琴:https://jsfiddle.net/avpv1ahr/1/

1 个答案:

答案 0 :(得分:1)

2D渲染上下文的.clip()方法只会缩小区域(另请参阅#14499)。因此,当您尝试删除下一个&#34; circle&#34;的区域时,第一个圆圈仍然有效。因此,您实际上看不到变化。

由于resetClip()未在多个当前浏览器中实现,因此您必须保存并恢复当前上下文状态:

function draw() {
    ctx.save(); // save the state

    circle = new Path2D();
    circle.arc(currX,currY,16,0,2*Math.PI);
    ctx.clip(circle);
    ctx.clearRect(0, 0, w, h);

    ctx.restore(); // restore the state
}

虽然您的代码已包含ctx.restore(),但它缺少ctx.save()