首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >2个画布上的globalCompositeOperation

2个画布上的globalCompositeOperation
EN

Stack Overflow用户
提问于 2018-12-05 07:09:40
回答 1查看 185关注 0票数 0

我有两个分层的画布,其中一个有一个圆,我想在任何时候看到。圆圈始终跟随鼠标。这个圆圈在上面,但是当另一个画布在上面画了一些东西(用相似的颜色)时,这个圆圈真的很难看到。我试过使用globalCompositeOperation,但它不起作用,圆圈仍然消失。

下面是一些代码:

代码语言:javascript
复制
    //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()

EN

回答 1

Stack Overflow用户

发布于 2018-12-05 20:01:51

因为你有两个重叠的canvas元素,所以你可以使用CSS和mix-blend-mode。我希望这就是你所需要的。

代码语言:javascript
复制
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)
  }
}
代码语言:javascript
复制
canvas{border:1px solid; position:absolute; top:0;left:0;}
#canvas1{mix-blend-mode: difference;}
代码语言:javascript
复制
<canvas id="canvas"></canvas>
<canvas id="canvas1"></canvas>

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53622774

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档