Hide object in canvas
Asked Answered
N

3

8

I want to know that, Is it possible to hide text object in canvas using fabric js?
I don't want to remove object, as I need it in further use, so just want to hide it. I searched a lot, but didn't work anything. Here is my code of fabric js.

var text = new fabric.Text("test", {
                    fontFamily: 'Times new roman',
                    fontSize: fabric.util.parseUnit(fontSize),
                    left: (startPosition.x + pointer.x) / 2,
                    top: ((startPosition.y + pointer.y) / 2) + 10,
                    slope: ((startPosition.y - pointer.y) / (startPosition.x - pointer.x)),
                    originX: 'center',
                    originY: 'center',
                });

canvas.add(text);
//canvas.getObjects(text).style.display = "none";
//text.prop.hide();
//text.hide = function () {
//text.set({
//        css: {"display":"none"},
//        selectable: false
//    });
//};

All suggestions are exceptable.

Nirvana answered 3/6, 2016 at 5:55 Comment(0)
V
3

In my case I've used opacity to show/hide object, not only text. Example:

if (logoPosition == 5) {
  logo.opacity = 0;
}
else {
  logo.opacity = 1;
}

P.S. do not forgot to re-render your canvas after that change. I've used canvas.renderAll();

Found this advice here: https://groups.google.com/forum/#!topic/fabricjs/cbdFgTH7UXc

Vinegary answered 6/8, 2017 at 11:54 Comment(1)
This method isn't so great if you already have custom opacity set on objects. Now you have to worry about storing/reverting opacity.Gherlein
O
3
text.visible = false;

From the Fabric Object class

https://github.com/fabricjs/fabric.js/blob/master/src/shapes/object.class.js#L409

Obbligato answered 15/6, 2022 at 21:52 Comment(0)
C
-1

Use Query Selector to hide the object.

// Pass the appropriate values to query selector of the canvas which we need to hide, In your code snippet you have given it as center, replace it with numeric values 

var query="canvas[x= fill the value of x ][y= fill the value of y][height= 'give the height'][width='give the width']";

// Finding the canvas
var canvas=document.querySelector(query);

// Hide the canvas
canvas.style.display="none";

Hope this helps

Cerebroside answered 3/6, 2016 at 6:4 Comment(4)
Thanks for quick reply, I have a query that as I have a text object, How can I get x,y,height & width of object?Nirvana
You would have placed this text object in the DOM, find the coordinates of that place where you have this object.Cerebroside
One more query, After setting display-none property, Will I get value of text object, even it is not displaying on canvas?Nirvana
Yes you should be able to get the value of text object, even if it is hidden.Cerebroside

© 2022 - 2024 — McMap. All rights reserved.