Fabric.js editing text via inputs

Home / Uncategorized / Fabric.js editing text via inputs

Question:
i am working on online print media application like ‘vistaprint.in’ where user can modify premade designs on fabric js canvas. in fabric.js object there is no unique identifier for objects…all the text objects create a input for each them so that user can directly change desired text by just changing in input…you can see in screenshot in right side of canvas there are input for each text object…what i am doing now is when input changes i loop through all text objects and match input text and text object text if it matches then i update new text to that object..this works fine for first time but not after that…i tried but unable to find what to do to solve this.

This is how canvas and input looks like now Screenshot of app

and this is the function which i created now for changing text of canvas
$(document).on(‘input’, ‘#cardalltexthex input’, function(){
v = $(this).attr(‘text’);
newtext = $(this).val();
objs = canvas.getObjects();
objs.forEach(function(e) {
if (e && e.type === ‘i-text’) {
console.log(e.text);
console.log(newtext);
if (e.text == v) {
e.setText(newtext);
canvas.renderAll();
}
}
});
});


Answer:
You need to specify id property to fabric object and check that property with your input as below sample

No need to do if (e.text == v) just set all fabric object with some unique id and compare that with your input.

var text;
var canvas;
canvas = new fabric.Canvas(‘c’);
text1 = new fabric.Text("Text", {
id: "cardalltexthex1",
fontSize: 70,
selectable: false,
left: 100,
top: 0,
text: "text1",
fill: ‘#f00’
});
canvas.add(text1);
text2 = new fabric.Text("Text", {
id: "cardalltexthex2",
fontSize: 70,
selectable: false,
left: 100,
top: 100,
text: "text2",
fill: ‘#f00’
});
canvas.add(text2);

$(‘.input’).on(‘keyup’, function() {
id = $(this).attr(‘id’);
val = $(this).attr(‘data-text’);
newtext = $(this).val();
input = $(this);

objs = canvas.getObjects();
objs.forEach(function(obj) {
if (obj && obj.text == val) {
obj.setText(newtext);
input.attr("data-text", newtext);
canvas.renderAll();
}
});
});

Run code snippetHide results
Expand snippet
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *