2个画布上的globalCompositeOperation

时间:2018-12-04 23:09:40

标签: javascript html5 html5-canvas

我有2个分层的画布,其中一个有一个我想一直看到的圆圈。圆圈始终跟随鼠标。圆圈在最上面,但是当另一块画布上画有某种颜色(具有相似的颜色)时,圆圈很难看到。我尝试使用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()

//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()

1 个答案:

答案 0 :(得分:-1)

由于有两个重叠的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>