我有两个分层的画布,其中一个有一个圆,我想在任何时候看到。圆圈始终跟随鼠标。这个圆圈在上面,但是当另一个画布在上面画了一些东西(用相似的颜色)时,这个圆圈真的很难看到。我试过使用globalCompositeOperation,但它不起作用,圆圈仍然消失。
下面是一些代码:
//pos is the mouse position {x:x,y:y}
ctx2.beginPath()
ctx2.globalCompositeOperation = "xor";
ctx1.globalCompositeOperation = "xor";
ctx2.shadowColor = brush.color
ctx2.shadowBlur = 1
ctx2.clearRect(0, 0, brush.prePos.x + brush.size*2, brush.prePos.y + brush.size*2)
ctx2.arc(pos.x, pos.y, brush.size / 4, 0, Math.PI*2)
ctx2.stroke()
ctx2.closePath()
发布于 2018-12-05 20:01:51
因为你有两个重叠的canvas元素,所以你可以使用CSS和mix-blend-mode。我希望这就是你所需要的。
const canvas = document.getElementById("canvas");
const canvas1 = document.getElementById("canvas1");
const ctx = canvas.getContext("2d");
const ctx1 = canvas1.getContext("2d");
let cw = canvas.width = canvas1.width = 300,
cx = cw / 2;
let ch = canvas.height = canvas1.height = 300,
cy = ch / 2;
let m;
ctx.fillStyle = "red"
ctx.beginPath();
ctx.fillRect(10,10,200,100);
canvas1.addEventListener("mousemove",(evt)=>{
m = oMousePos(canvas1, evt);
ctx1.clearRect(0,0,cw,ch);
ctx1.beginPath();
ctx1.arc(m.x,m.y,20,0,2*Math.PI);
ctx1.fillStyle = "red"
ctx1.fill();
})
function oMousePos(canvas, evt) {
var ClientRect = canvas.getBoundingClientRect();
return { //objeto
x: Math.round(evt.clientX - ClientRect.left),
y: Math.round(evt.clientY - ClientRect.top)
}
}canvas{border:1px solid; position:absolute; top:0;left:0;}
#canvas1{mix-blend-mode: difference;}<canvas id="canvas"></canvas>
<canvas id="canvas1"></canvas>
https://stackoverflow.com/questions/53622774
复制相似问题