如何在canvas的元素上正确应用globalCompositeOperation?

时间:2017-04-17 16:41:39

标签: javascript canvas fabricjs globalcompositeoperation

我遇到了 globalCompositeOperation 的问题。

我的目标是让Blue元素仅显示在Red元素内部,并且根本不应该在Red矩形之外可见(类型为Overflow-Hidden效果)。另外,红色和蓝色都必须具有转换能力(两者都可编辑)。

如您所见,如果我在画布中添加一个元素(黄色元素),则在黄色和蓝色重叠的区域中可以看到蓝色元素。

http://jsfiddle.net/redlive/q4bvu0tb/1/

var canvas = new fabric.Canvas('c');


var yellow = new fabric.Circle({
  top: 200,
  left: 0,
  radius: 100,
  strokeDashArray: [5, 5],
  stroke: 'black',
  strokeWidth: 5,
  fill: 'yellow'
});
canvas.add(yellow);


var red = new fabric.Rect({
  top: 0,
  left: 0,
  width: 300,
  height: 300,
  strokeDashArray: [5, 5],
  stroke: 'black',
  strokeWidth: 5,
  fill: 'red',
  rx: 40
});
canvas.add(red);


var blue = new fabric.Circle({
  top: 150,
  left: 80,
  radius: 100,
  strokeDashArray: [5, 5],
  stroke: 'black',
  strokeWidth: 5,
  fill: 'blue',
    globalCompositeOperation: 'source-atop'
});
canvas.add(blue);



var green = new fabric.Circle({
  top: 0,
  left: 0,
  radius: 100,
  strokeDashArray: [5, 5],
  stroke: 'black',
  strokeWidth: 5,
  fill: 'green'
});
canvas.add(green);

强制性条件:

  • 在Canvas上保留元素外观。
  • 没有剪辑(因为剪辑 不允许在同一时间添加背景颜色和图像)

1 个答案:

答案 0 :(得分:1)

使用以下步骤可以实现......

  • 在绘制yellow一个
  • 之前删除blue元素
  • 绘制blue元素后,将yellow元素的globalCompositeOperation设置为destination-over并将其添加回来

var canvas = new fabric.Canvas('c');

var yellow = new fabric.Circle({
  top: 200,
  left: 0,
  radius: 100,
  strokeDashArray: [5, 5],
  stroke: 'black',
  strokeWidth: 5,
  fill: 'yellow'
});
canvas.add(yellow);

var red = new fabric.Rect({
  top: 0,
  left: 0,
  width: 300,
  height: 300,
  strokeDashArray: [5, 5],
  stroke: 'black',
  strokeWidth: 5,
  fill: 'red',
  rx: 40
});
canvas.add(red);

canvas.remove(yellow); //remove yellow

var blue = new fabric.Circle({
  top: 150,
  left: 80,
  radius: 100,
  strokeDashArray: [5, 5],
  stroke: 'black',
  strokeWidth: 5,
  fill: 'blue',
  globalCompositeOperation: 'source-atop'
});
canvas.add(blue);

yellow.set({globalCompositeOperation: 'destination-over'}); //set gCO for yellow
canvas.add(yellow); //add yellow back

var green = new fabric.Circle({
  top: 0,
  left: 0,
  radius: 100,
  strokeDashArray: [5, 5],
  stroke: 'black',
  strokeWidth: 5,
  fill: 'green'
});
canvas.add(green);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<canvas id="c" width="800" height="800"></canvas>