Reputation: 329
I need to mask all canvas objects using one layer. Layer is a png file which I loading from URL. What is the best approach for this?
Tried this way. But I need to clip every object. And I think this is not the proper way to do this.
<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();
});
Upvotes: 3
Views: 5804
Reputation: 4671
i created a jsfiddle where i create some objects and i assign pattern to them. is that what you need?
if so, i show a snippet below and my jsfiddle exmaple.
javascript , actually the main code:
var canvas = new fabric.Canvas('c');
canvas.backgroundColor = 'yellow';
//create circle object
var circle = new fabric.Circle({
radius: 60,
fill: 'red',
left: 50,
top: 100
});
canvas.add(circle);
addPattern(circle);
//create square object
var square = new fabric.Rect({
left: 180,
top: 140,
fill: 'green',
width: 140,
height: 180
});
canvas.add(square);
addPattern(square);
canvas.renderAll();
function addPattern(obj){
fabric.util.loadImage('http://fabricjs.com/assets/pug_small.jpg', function (img) {
obj.fill = new fabric.Pattern({
source: img,
repeat: 'no-repeat'
});
canvas.renderAll();
});
}
jsfiddle: http://jsfiddle.net/tornado1979/t6vf5z5w/
Upvotes: 0
Reputation: 558
fabric.loadSVGFromURL('/userboards/board-img/mask-no-dots.svg', function(objects,options){
$scope.overlayPath = new fabric.util.groupSVGElements(objects,options);
$scope.$apply();
}, function(item, object){
});
$scope.cutByMask = function(){
if($scope.overlayPath){
canvas.remove($scope.overlayPath);
}
$scope.overlayPath
//.scaleToHeight(533)
.set({
//left: 797, top: 1368,
scaleX: $scope.zoom / 100, scaleY: $scope.zoom / 100
//, width: 2811, height: 533
})
.setCoords();
canvas.centerObject($scope.overlayPath);
canvas.add($scope.overlayPath);
canvas.moveTo($scope.overlayPath, 0);
canvas.remove($scope.overlayPath);
canvas.clipTo = function(ctx) {
if($scope.overlayPath){
$scope.overlayPath.render(ctx);
}
};
canvas.renderAll();
};
Variant with SVG mask. Here you load SVG mask (SVG with only one path), and then all your images will be cropped by this mask.
I don't found variant with cropping by PNG, but if you need it - you shoud use it in
canvas.clipTo
Upvotes: 0