问题
In fabric-js, i am making Group of Rect and text field and then adding it to the canvas. i am using following code , but can i change the Text of text field once it is added in canvas .
I have made Fiddle Please Check,
http://jsfiddle.net/HAb4N/5/
var canvas = new fabric.Canvas('c');
var Bar = new fabric.Text('Bar', {selectable: false, top: 50, left: 10});
var rect = new fabric.Rect({width: 100, height: 100, left: 100, top: 100, fill: 'red'});
var group = new fabric.Group([rect, Bar], {selectable: true, top: 50, left: 100});
canvas.add(group);
canvas.renderAll();
$(document).click(function(e) {
console.log('click');
console.log('ActiveObject', canvas.getActiveObject());
console.log('ActiveGroup', canvas.getActiveGroup());
Bar.set('Text','Selectedoooooooo');
});
回答1:
This works for me:
Bar.setText("my_text");
canvas.renderAll();
回答2:
When using the "set" function try camelcase for the first argument!
In other words change:
Bar.set('Text','Selectedoooooooo');
to:
Bar.set('text','Selectedoooooooo');
This works for me 🙏🏼
回答3:
Yes you can set text once it is added to canvas.Here is the jsfiddle
try changing your
Bar.set('Text','Selectedoooooooo');
to
Bar.setText('Selectedoooooooo');
Hope it helps....
回答4:
Hope this will help select first object then enter text in text area
<canvas id="c" width="600" height="200"></canvas>
<textarea id="textinput" name="textarea" placeholder="Enter Text"> </textarea>
var canvas = new fabric.Canvas('c');
document.getElementById('textinput').addEventListener('keyup', function (e) {
var obj = canvas.getActiveObject();
if (!obj) return;
obj.setText(e.target.value);
canvas.renderAll();
});
var text = new fabric.Text('Your Text Here', { left: 400, top: 200,fill:'#A0A0A0'});
canvas.add(text);
var rect = new fabric.Rect({width: 100, height: 200, left: 200, top: 100, fill:'red'});
var group = new fabric.Group([rect,text], {selectable: true, top: 50, left: 350});
canvas.add(group);
canvas.renderAll();
回答5:
You can access children of a group via getObjects()
or item()
methods:
canvas.on('object:selected', function(e) {
e.target.item(1).setText('Selectedoooooooo');
});
See http://jsfiddle.net/fabricjs/HAb4N/12/
回答6:
Use the new IText in FabricJS. Here is a nice solution
This is my answer to it
addText(color) {
color = color ? color : '#333';
let textEl = new fabric.IText('', {
fontFamily: 'Open Sans',
fill: color,
fontSize: 50
});
this.canvas.add(textEl).setActiveObject(textEl);
textEl.enterEditing();
}
来源:https://stackoverflow.com/questions/18864487/change-text-once-it-is-added-on-canvas