我对 globalCompositeOperation 有疑问。
我的目标是让蓝色元素仅显示在红色元素内部,并且根本不应该在红色矩形外部可见(有点溢出隐藏效果)。另外,红色和蓝色都必须具有转换能力(都是可编辑的)。
如您所见,如果我再向 Canvas 中添加一个元素(黄色元素),蓝色元素将在黄色和蓝色重叠的区域可见。
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 上的外观。
- 无裁剪(因为裁剪 不允许同时添加背景颜色和图像)
最佳答案
可以通过以下步骤完成...
- 在绘制
蓝色
元素之前移除黄色
元素 - 绘制完
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>
关于javascript - 如何在 Canvas 元素上正确应用 globalCompositeOperation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43455582/