Reputation: 81
In Fabric JS, I have made a canvas application which allows other users to upload there own image and Try Sun Glasses On .
But the problem is the Uploaded Image Overlaps with the sun glasses image and hence the sunglasses image is not visible.
Is there any way to keep the sun glass image always on top (Something like Z - Index in Fabric JS)
Upvotes: 4
Views: 8701
Reputation: 1233
FabricJS has an overlay image feature - it is discussed on page 4 of the introduction, and can be found here: http://fabricjs.com/fabric-intro-part-4/. The code example they provide is:
canvas.add(new fabric.Circle({ radius: 30, fill: '#f55', top: 100, left: 100 }));
canvas.setOverlayImage('../assets/jail_cell_bars.png', canvas.renderAll.bind(canvas));
Documentation link: http://fabricjs.com/docs/fabric.Canvas.html#overlayImage
In my personal experience, I have had issues in getting the overlay image to work just right... I forget what my issue was really. For that reason, what I've done is looped through the objects on the canvas and manually set the stacking order as needed. Depending on the size of your canvas this could have performance issues of course.
Another manual approach to this would be to select that object directly and then use the bring to front method to ensure it's on top.
To select an object directly, you could use this code (it does require a javascript library lodash so you'll need to load this to the page as well).
/* Find first object in canvas that has a specific property value */
function findObjectWithPropertyValue(canvas, propertyName, propertyValue) {
var condition = {};
condition[propertyName] = propertyValue;
return _(canvas.getObjects()).filter( condition ).first()
}
Call this function setting propertyName with the object attribute you want to target this item by. Name might be a good option. propertyValue is the value of propertyName that you are targeting. The object for that layer element within the Fabricjs canvas will be returned.
Note: I'm passing in the canvas to this function because where I use this I have multiple canvases on the page at once. If you only have one canvas you could modify this a bit to get rid of having to pass that into the function.
Once you have selected the object with this function, then you'd be able to simply move it to the front.
canvas.bringToFront(myObject)
To put this into a full example, assuming your sunglasses overlay image object has a name of glasses_overlay, your code would look something like this:
var glassesOverlayObj = findObjectWithPropertyValue(canvas, 'name', 'glasses_overlay);
canvas.bringToFront(glassesOverlayObj);
Simply run this after a new image has been uploaded and just before you render the canvas. The user will never see that they were stacked out of order.
Upvotes: 4