FabricJS - 自由绘图模式下的Canvas混合模式

时间:2016-08-04 10:01:00

标签: javascript canvas html5-canvas fabricjs blending

使用无面料时,我希望使用不透明度向画布添加不同的线条。当相互绘制时,这些线不应该加上它们的不透明度。因此我将画布混合模式更改为xor。无论如何,当相互画线时,不透明度仍会增加。我在这里做错了什么?

var canvas = new fabric.Canvas("a", {
		isDrawingMode : true
});

document.getElementById("cbFreeDrawing").onchange = function () {
  canvas.isDrawingMode = this.checked;
};

canvas.setBackgroundImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas));

canvas.freeDrawingBrush.width = 25;
canvas.freeDrawingBrush.color = "rgba(255,0,0,.5)";
//this seems not to work
canvas.getContext().globalCompositeOperation = 'xor';
canvas {
  border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.3/fabric.min.js"></script>
Drawing Mode: <input id="cbFreeDrawing" type="checkbox" checked="true"/><br/>
<canvas id="a" width="400" height="300"></canvas>

2 个答案:

答案 0 :(得分:4)

在freeDrawing中,您正在upperCanvasEl上绘制,这是一个放在lowerCanvasEl上方的画布元素。 这些元素的上下文随时可以进入属性: canvas.contextTopcanvas.contextContainer

您可以做的是将单个路径globalCompositeOperation设置为&#39; xor&#39;当它传递给lowerCanvas时。您可以使用一个事件(路径:已创建)。 我在一个单独的画布中移动了背景(但它可能只是放在画布下面的图像),因此这些线条与背景本身并不相符。

&#13;
&#13;
var canvas = new fabric.Canvas("a", {
		isDrawingMode : true
});
var canvas2 = new fabric.StaticCanvas("b");
canvas.lowerCanvasEl.parentNode.appendChild(canvas2.lowerCanvasEl)

document.getElementById("cbFreeDrawing").onchange = function () {
  canvas.isDrawingMode = this.checked;
};
canvas.on('path:created', function(opt) {
  opt.path.globalCompositeOperation = 'xor';
  canvas.renderAll();
});
canvas2.setBackgroundImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas2.renderAll.bind(canvas2));

canvas.freeDrawingBrush.width = 25;
canvas.freeDrawingBrush.color = "rgba(255,0,0,.5)";
//this seems not to work
canvas.contextTop.globalCompositeOperation = 'xor';
&#13;
canvas {
  border: 1px solid;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.3/fabric.min.js"></script>
Drawing Mode: <input id="cbFreeDrawing" type="checkbox" checked="true"/><br/>
<canvas id="a" width="400" height="300"></canvas>
<canvas id="b" width="400" height="300"></canvas>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

+ AndreaBogazzi刚刚发现答案仅在不透明度为.5时有效,如果设置为另一个值不透明度重叠/组合/表现为另一种方式。

小提琴(简化以便更好地理解):https://jsfiddle.net/c8mf391q/

var canvas = new fabric.Canvas("a", {
        isDrawingMode : true
});



canvas.on('path:created', function(opt) {
  opt.path.globalCompositeOperation = 'xor';
  canvas.renderAll();
});


canvas.freeDrawingBrush.width = 25;
canvas.freeDrawingBrush.color = "rgba(255,0,0,.3)";