【发布时间】:2015-12-01 21:31:47
【问题描述】:
我需要使用一层来掩盖所有画布对象。图层是我从 URL 加载的 png 文件。最好的方法是什么?
试过这种方式。但我需要剪辑每个对象。而且我认为这不是正确的做法。
<button id="btnAddText" >Add Text</button>
<canvas id="divPad" style="height: 500px; width: 500px"></canvas>
var canvas = new fabric.Canvas('divPad', {
width: $("#divPad").width(),
height: $("#divPad").height()
});
$("#btnAddText").click(function () {
var text = new fabric.Text("Testing", {
fontSize: 50,
fill: "green",
top: 50,
left:50
});
canvas.add(text);
text.globalCompositeOperation = 'source-atop';
canvas.renderAll();
});
var background;
fabric.Image.fromURL('http://www.clipartbest.com/cliparts/Rid/Bjo/RidBjoni9.png', function (objects, options) {
background = objects;
background.set({
left: 0,
top: 0,
scaleY: canvas.height / background.width,
scaleX: canvas.width / background.width,
selectable: false
});
canvas.add(background);
canvas.renderAll();
});
【问题讨论】:
-
据我了解,无法通过 PNG 剪辑。但是,如果您可以创建单路径 SVG - 这很简单)
-
使用
image.globalCompositeOperation = 'source-atop';是正确的方法。掩蔽图像应该是最后绘制到画布上的图像。 -
你的方法已经不错了。你不会发现任何更简单的东西。绘制 png 形状,将 globalCompositeOperation 设置为“source-atop”,绘制艺术品,然后将 globalCompositeOperation 重置为“source-over”