Sunil Meena
Sunil Meena

Reputation: 541

Fabric.js editing text via inputs

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(); 
     }
   }
 });
});

Upvotes: 0

Views: 4660

Answers (1)

Yogen Darji
Yogen Darji

Reputation: 3300

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();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.17/fabric.min.js"></script>

<canvas id="c" width=500 height=250></canvas>

<input class="input" data-text="text1" value="text1" id="cardalltexthex1" />

<input class="input" data-text="text2" value="text2" id="cardalltexthex2" />

Upvotes: 2

Related Questions