Deleting all zero-opacity elements in Fabricjs - javascript

I'm using the fabricjs animate function to change the opacity of text elements on a canvas.
For every frame, I need to check for elements with 0% opacity and remove them with canvas.remove.
At the moment, I've come up with this code which I'm running for each fire of requestAnimationFrame:
canvas.getObjects().filter((obj) => obj.get("opacity") === 0).forEach(canvas.remove)
However, when iterating, filtering through the items and running canvas.remove, I'm getting Uncaught TypeError: Cannot read property 'indexOf' of undefined.
Here's a simple implementation of this problem (not the actual code):
const canvas = new fabric.StaticCanvas(document.querySelector("canvas"), { backgroundColor: "black" })
// CODE HERE:
function removalLogic() {
canvas.getObjects().filter((obj) => obj.get("opacity") === 0).forEach(canvas.remove)
}
const rect = new fabric.Rect({
width: 100, height: 100,
left: 10, top: 20,
fill: "grey",
})
canvas.add(rect)
rect.animate("opacity", "0", {
duration: 2500,
onChange: canvas.renderAll.bind(canvas),
onComplete: removalLogic,
})
<canvas height="512" width="512"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.5.0/fabric.min.js"></script>

Use .map() to iterate over all the objects of canvas.
Use canvas.remove(obj) to remove the object.
This statement of yours was incorrect obj.get("opacity") === 0).forEach
const canvas = new fabric.StaticCanvas(document.querySelector("canvas"), { backgroundColor: "black" })
// CODE HERE:
function removalLogic() {
console.log(canvas.getObjects().length);
canvas.getObjects().map((obj) => ((obj.get("opacity") == 0)? canvas.remove(obj) :''))
console.log(canvas.getObjects().length);
}
const rect = new fabric.Rect({
width: 100, height: 100,
left: 10, top: 20,
fill: "grey",
})
canvas.add(rect)
rect.animate("opacity", "0", {
duration: 2500,
onChange: canvas.renderAll.bind(canvas),
onComplete: removalLogic,
})
<canvas height="512" width="512"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.5.0/fabric.min.js"></script>

Related

Jointjs trigger action when hovering a markup selector of cell

I know that it's pretty easy to trigger an action in JointJS if you click a markup selector. We can simply add a custom event attr of that markup element, but as far as I know only pointer events are allowed. Is there any way to archive the same for hovering?
For example I have a custom cell with 4 buttons, that are just a bunch of svg tag added via the markup. I want to change the opacity of all other elements on the canvas, depending on the button that was hovered. I have an idea on how to filter everything and change the opacity, but I have no idea on how to trigger that event and know what selector I'm hovering.
You could take advantage of the 'element:mouseenter' event on the paper, then event.target can give you access to sub-elements on the shape.
In the following example, when you hover a color on the button shape, the standard.Rectangle type shapes all change to that color.
This solution takes advantage of adding classes via markup, and checking if the target has the particular class.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jointjs/3.6.5/joint.css" />
<style>
.joint-paper {
display: inline-block;
border: 1px solid gray;
}
</style>
</head>
<body>
<!-- content -->
<div id="myholder"></div>
<!-- dependencies -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.4.1/backbone.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jointjs/3.6.5/joint.js"></script>
<!-- code -->
<script type="text/javascript">
var namespace = joint.shapes;
var graph = new joint.dia.Graph({}, { cellNamespace: namespace });
var paper = new joint.dia.Paper({
el: document.getElementById('myholder'),
model: graph,
width: 600,
height: 300,
gridSize: 1,
cellViewNamespace: namespace
});
class ButtonShape extends joint.dia.Element {
defaults() {
return {
...super.defaults,
type: 'MyShape',
size: {
width: 120,
height: 155
},
attrs: {
body: {
width: 'calc(w)',
height: 'calc(h)',
fill: '#ffffff',
stroke: '#333333',
strokeWidth: 2,
rx: 5,
ry: 5,
pointerEvents: 'none'
},
rectUpper: {
width: 'calc(0.8*w)',
height: 'calc(h/2.5)',
fill: 'cornflowerblue',
stroke: '#333333',
strokeWidth: 2,
x: 'calc(0.1*w)',
y: 10
},
rectLower: {
width: 'calc(0.8*w)',
height: 'calc(h/2.5)',
fill: 'tomato',
stroke: '#333333',
strokeWidth: 2,
x: 'calc(0.1*w)',
y: 'calc(h - calc(h/2.5 + 10))'
},
}
};
}
preinitialize() {
this.markup = [{
tagName: 'rect',
selector: 'body'
}, {
tagName: 'rect',
selector: 'rectUpper',
className: 'upper'
}, {
tagName: 'rect',
selector: 'rectLower',
className: 'lower'
}];
}
}
const buttonShape = new ButtonShape();
buttonShape.position(10, 10);
buttonShape.addTo(graph);
for(let i = 0; i < 5; i++) {
const rect = new joint.shapes.standard.Rectangle();
rect.position(i * 60 + 10, 200);
rect.resize(50, 50);
rect.addTo(graph);
}
paper.on('element:mouseenter', function (cellView, evt) {
const rectangles = graph.getElements().filter((el) => el.get('type') === 'standard.Rectangle');
if (evt.target.classList.contains('upper')) {
rectangles.forEach((rect) => {
rect.attr('body/fill', 'cornflowerblue')
});
}
if (evt.target.classList.contains('lower')) {
rectangles.forEach((rect) => {
rect.attr('body/fill', 'tomato')
});
}
});
</script>
</body>
</html>

FabricJS modify custom properties

I am using the FabricJS graphics library and have added an additional property (name) to a fabric.Rect object. All well and good and it serializes out to JSON correctly.
I am struggling though with the code needed to allow me to subsequently change the customer property once set i.e. to change 'some name' to something else. It is driving me a bit crazy.
Any additional help really appreciated.
Thanks,
Shaun
const o = new fabric.Rect({
width: width,
height: height,
fill: tableFill,
stroke: tableStroke,
strokeWidth: 2,
shadow: tableShadow,
originX: "center",
originY: "center",
centeredRotation: true,
snapAngle: 45,
selectable: true,
strokeUniform: true
});
o.toObject = (function(toObject) {
return function(propertiesToInclude) {
return fabric.util.object.extend(toObject.call(this, propertiesToInclude), {
name: 'some name'
});
};
})(o.toObject);
console.log(o.toObject().name)
So, basically run this code to allow any additional properties to be serialised to and from JSON. In this example a property called name is added.
const originalToObject = fabric.Object.prototype.toObject;
const myAdditional = ['name'];
fabric.Object.prototype.toObject = function (additionalProperties) {
return originalToObject.call(this, myAdditional.concat(additionalProperties));
}
Then create a new Fabric object and set or get the additional properties as needed...
const o = new fabric.Rect({
width: width,
height: height,
fill: tableFill,
stroke: tableStroke,
strokeWidth: 2,
shadow: tableShadow,
originX: "center",
originY: "center",
centeredRotation: true,
snapAngle: 45,
selectable: true,
strokeUniform: true
});
o.name = 'Fred'
console.log(o.toJSON())

Show full text outside group object fabricjs

I am trying to merge textbox and group in fabricjs
when I set text, It doesn't show full text.
how to set full text?
var iText4 = new fabric.Textbox('Text noasasasasasasasasasabcdefghxyz', {
left: 50,
top: 100,
fontFamily: 'Helvetica',
width: 30,
styles: {
0: {
0: { textBackgroundColor: 'blue', fill: 'green' },
1: { textBackgroundColor: '#faa' },
2: { textBackgroundColor: 'lightblue' },
}
}
});
var group = new fabric.Group([ iText4 ], {
left: 150,
top: 100,
width: 60,
});
var canvas = new fabric.Canvas('c');
canvas.add(group);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.3/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id='c' width='500' height='400'></canvas>
The group's width is smaller than the text's width, causing it to be cut off. Removing it should solve your problem.
var group = new fabric.Group([ iText4 ], {
left: 150,
top: 100
});
See here: https://jsfiddle.net/p6c2trg8/1/

Joint JS - How apply an event on shapes.devs

I'm new with jointjs and I try to constraint a rectangle with ports to a line.
I tried to reproduce tutorial, that works with a basic.Circle, with a basic.Rect but not with devs.Model
Could someone explian me why and how to solve this problem?
Many thanks in advance!
Here is my code :
var width=400, height=1000;
var ConstraintElementView = joint.dia.ElementView.extend({
pointermove: function(evt, x, y) {
joint.dia.ElementView.prototype.pointermove.apply(this, [evt, 100, y]);
}
});
var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({ el: $('#myholder'), width: width, height: height, gridSize: 1, model: graph, elementView: ConstraintElementView});
var m1 = new joint.shapes.devs.Model({
position: { x: 20, y: 20 },
size: { width: 90, height: 90 },
inPorts: [''],
outPorts: [''],
attrs: {
'.label': { text: 'Model', 'ref-x': .4, 'ref-y': .2 },
rect: { fill: '#2ECC71' },
'.inPorts circle': { fill: '#16A085' },
'.outPorts circle': { fill: '#E74C3C' }
}
});
var m2=m1.clone();
m2.translate(0,300);
var earth = new joint.shapes.basic.Circle({
position: { x: 100, y: 20 },
size: { width: 20, height: 20 },
attrs: { text: { text: 'earth' }, circle: { fill: '#2ECC71' } },
name: 'earth'
});
graph.addCell([m1, m2, earth]);
Why does it not work?
devs.Model is not rendered via ContraintElementView to the paper.
devs.Model uses devs.ModelView for rendering, basic.Circle and basic.Rect use ContraintElementView.
JointJS dia.Paper searches for a view defined in the same namespace as the model first. If found, it uses it. It uses one from the paper elementView option otherwise. i.e. joint.shapes.devs.ModelView found for devs.Model but no view found for basic.Circle (no joint.shapes.basic.RectView is defined)
How to make it work?
define elementView paper option as a function. In that case paper don't search the namespace and uses the result of the function first.
Note that in order to render ports devs.ModelView is still required.
i.e.
var paper = new joint.dia.Paper({
elementView: function(model) {
if (model instanceof joint.shapes.devs.Model) {
// extend the ModelView with the constraining method.
return joint.shapes.devs.ModelView.extend({
pointermove: function(evt, x, y) {
joint.dia.ElementView.prototype.pointermove.apply(this, [evt, 100, y]);
}
});
}
return ConstraintElementView;
}
});
http://jsfiddle.net/kumilingus/0bjqg4ow/
What is the recommended way to do that?
JointJS v0.9.7+
not to use custom views that restrict elements movement
use restrictTranslate paper option instead.
i.e.
var paper = new joint.dia.Paper({
restrictTranslate: function(elementView) {
// returns an area the elementView can move around.
return { x: 100, y: 0, width: 0, height: 1000 }
};
});
http://jsfiddle.net/kumilingus/atbcujxr/
I think this could help you :
http://jointjs.com/demos/devs

Titanium mobile Javascript objects

Ok so I'm new to Titanium and I'm pretty much a noob at Javascript
I tried doing this:
app.view.newMatrix = function() {
return {
matrix = Titanium.UI.createWindow({
title:'Add a New Matrix',
backgroundColor:'stripped',
navBarHidden: false
}),
// navbar buttons
cancel = Titanium.UI.createButton({
title:'Cancel'
}),
save = Titanium.UI.createButton({
title:'Save',
style:Titanium.UI.iPhone.SystemButton.SAVE
}),
name_label = Titanium.UI.createLabel({
text: "Matrix Name:",
font: { fontsize: 12, fontstyle: 'italic', color: '#336699' },
height: 35,
top: 35,
left: 30,
width: 150,
color: "black"
}),
name = Titanium.UI.createTextArea({
color: '#336699',
height: this.name_label.height,
top: this.name_label.top + 35,
left: this.name_label.left - 10,
width: 275,
borderRadius:15
}),
setItems = function() {
this.win.add(this.name);
this.win.add(this.name_label);
this.win.add(this.desc);
this.win.add(this.desc_label);
Ti.API.info("label:"+ this.name_label.height);
return this.win.open({modal: true, animation: true});
}
}
}
then called it like this:
app.controller.home = function() {
var home = app.view.home();
home.setItems();
home.butn.addEventListener("click", function(e){
app.controller.newMatrix();
});
home.butn2.addEventListener("click", function (e) {
matrix_table(tab);
});
home.butn3.addEventListener("click", function(e){
newItem();
});
home.butn5.addEventListener("click", function (e) {
item_table();
});
}
I did this because I saw a Titanium MVC suggestion here but I don't get why it returns an anonymous object. I can't access properties like name_label from within the name object.
I figured out that I should do this instead:
app.view.newMatrix = function() {
this.matrix = Titanium.UI.createWindow({
title:'Add a New Matrix',
backgroundColor:'stripped',
navBarHidden: false
}),
// navbar buttons
this.cancel = Titanium.UI.createButton({
title:'Cancel'
}),
this.save = Titanium.UI.createButton({
title:'Save',
style:Titanium.UI.iPhone.SystemButton.SAVE
}),
this.name_label = Titanium.UI.createLabel({
text: "Matrix Name:",
font: { fontsize: 12, fontstyle: 'italic', color: '#336699' },
height: 35,
top: 35,
left: 30,
width: 150,
color: "black"
}),
this.name = Titanium.UI.createTextArea({
color: '#336699',
height: this.name_label.height,
top: this.name_label.top + 35,
left: this.name_label.left - 10,
width: 275,
borderRadius:15
}),
this.setItems = function() {
this.win.add(this.name);
this.win.add(this.name_label);
this.win.add(this.desc);
this.win.add(this.desc_label);
Ti.API.info("label:"+ this.name_label.height);
return this.win.open({modal: true, animation: true});
}
}
and call it like this:
app.controller.home = function() {
return {
getView: function() {
var home = app.view.home();
home.setItems();
home.butn.addEventListener("click", function(e){
app.controller.newMatrix();
});
home.butn2.addEventListener("click", function (e) {
matrix_table(tab);
});
home.butn3.addEventListener("click", function(e){
newItem();
});
home.butn5.addEventListener("click", function (e) {
item_table();
});
}
}
}
But I don't know why the first example doesn't work. I mean aren't properties the same as variables? Also I do know that the second example is an object too.. is that how I'm supposed to do them? Also with the second example is the new keyword optional? Should I use it? I kinda wanted to stay away from that cause I'm not sure when I should use it.
thanks I hope I made sense. I do have it working but I don't know if the second example is the right way to go....

Categories

Resources