我正在尝试制作一个分层绘图应用程序( Canvas 上有东西,后面有东西),我想删除并透视 z-index 顶部的 Canvas 。但由于某种原因 onmousemove 我无法让它继续。
我认为我在绘制方法中处理 Canvas 的方式有问题,但我不确定。
下面的代码将一个 Canvas 放在另一个 Canvas 上,上面是蓝色,下面是红色,目的是在鼠标移动时用圆形删除上面的蓝色 Canvas ,以便删除使用鼠标在 Canvas 上移动,就像在 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()时起作用,而在之后不起作用?
我在这里设置了一个 fiddle :https://jsfiddle.net/avpv1ahr/1/
最佳答案
.clip()
2D 渲染上下文的方法仅减少区域(另请参见 #14499 )。因此,当您尝试删除下一个“圆”的区域时,第一个圆仍然有效。因此,您实际上并没有看到任何变化。
由于当前的多个浏览器未实现 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()
。
关于javascript - 在 Canvas 上用圆圈删除以查看 z 索引上其后面的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33805155/