Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript GlobalComposite在2张画布上进行操作_Javascript_Html_Html5 Canvas - Fatal编程技术网

Javascript GlobalComposite在2张画布上进行操作

Javascript GlobalComposite在2张画布上进行操作,javascript,html,html5-canvas,Javascript,Html,Html5 Canvas,我有两个层次的画布,其中一个有一个圆圈,我想在任何时候都看到。圆圈始终跟随鼠标。圆圈在上面,但是当另一张画布上画了一些东西(颜色相似)时,圆圈就很难看到了。我尝试过使用globalCompositeOperation,但不起作用,圆圈仍然消失 下面是一些代码: //pos is the mouse position {x:x,y:y} ctx2.beginPath() ctx2.globalCompositeOperation = "xor"; ctx1.glo

我有两个层次的画布,其中一个有一个圆圈,我想在任何时候都看到。圆圈始终跟随鼠标。圆圈在上面,但是当另一张画布上画了一些东西(颜色相似)时,圆圈就很难看到了。我尝试过使用
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()

由于您有两个重叠的
画布
元素,因此可以使用CSS
混合模式
。我希望这就是你需要的

const canvas=document.getElementById(“canvas”);
const canvas1=document.getElementById(“canvas1”);
const ctx=canvas.getContext(“2d”);
const ctx1=canvas1.getContext(“2d”);
让cw=canvas.width=canvas1.width=300,
cx=cw/2;
让ch=canvas.height=canvas1.height=300,
cy=ch/2;
让m;
ctx.fillStyle=“红色”
ctx.beginPath();
ctx.fillRect(10,10200100);
canvas1.addEventListener(“mousemove”(evt)=>{
m=oMousePos(canvas1,evt);
ctx1.clearRect(0,0,cw,ch);
ctx1.beginPath();
ctx1.弧(m.x,m.y,20,0,2*数学π);
ctx1.fillStyle=“红色”
ctx1.fill();
})
功能oMousePos(画布、evt){
var ClientRect=canvas.getBoundingClientRect();
返回{//objeto
x:Math.round(evt.clientX-ClientRect.left),
y:Math.round(evt.clientY-ClientRect.top)
}
}
canvas{边框:1px实体;位置:绝对;顶部:0;左侧:0;}
#canvas1{混合模式:差异;}


globalCompositeOperation仅在已设置的上下文中为下一个图形设置合成模式。一旦生成了图像,它就不会在表示级别执行任何操作(比如css属性)。但是对于您的问题,您不只是想将带有圆的画布放置在比另一个更高的z索引处吗?如果这不起作用,那么请进一步说明你的两张画布应该如何进行互操作。这是否适用于fillStyle和strokeStyle?当我尝试应用混合模式时,我发现没有任何改变。样式被覆盖,所以我修复了它。