amit gupta
amit gupta

Reputation: 1330

Change text of canvas without using canvas.getActiveObject() method

without clicking on the canvas area, I want to change text once it is added on canvas. in my code i have to select canvas text first and then it change on typing in textarea. here is my code: //html

    <canvas id="c" width="400" height="200"></canvas>
    <br>
    Change Text :
    <textarea  style="margin:0px;" id="textinput" rows="5"  ></textarea>

//script

    var canvas = new fabric.Canvas('c');
var text = new fabric.Text('Honey', {
  fontSize: 100,
  left: 50,
  top: 50,
  lineHeight: 1,
  originX: 'left',
  fontFamily: 'Helvetica',
  fontWeight: 'bold'
});
canvas.add(text);

$("#textinput").keyup(function(event) {
//document.getElementById('textinput').addEventListener('keyup', function (e) {
  // alert("hi");
    var obj = canvas.getActiveObject();
    if (!obj) return;
    obj.setText(event.target.value);
    canvas.renderAll();
});

//Css

 canvas {  border:1px solid #000; }
.controles {  margin:50px 0;   }

Any one have any idea how to do this ? Here is my Fiddle Demo.

Upvotes: 2

Views: 2459

Answers (2)

Sergiu Paraschiv
Sergiu Paraschiv

Reputation: 10153

How about

var text = new fabric.Text('Honey', {
  ...
});
canvas.add(text);

$("#textinput").keyup(function(event) {
    text.setText(event.target.value);
    canvas.renderAll();
});

As long as you have a reference to text you don't need anything else.

Upvotes: 2

Matthew Riches
Matthew Riches

Reputation: 2286

This should do the trick:

canvas.getObjects()[0].text = "Boo Boo";
canvas.renderAll();

Here's a fiddle: http://jsfiddle.net/xadqg/

This of course will get the first object, but since you only have one this should be fine.

Feel free to change Boo Boo to whatever you want like $(this).val()

Upvotes: 2

Related Questions