mel*_*war 65
最新版本的fabric.js包含一个IText类,它包含了动态编辑和选择文本的交互.尝试使用最新版本的fabric.js下面的代码
canvas.add(new fabric.IText('Tap and Type', {
fontFamily: 'arial black',
left: 100,
top: 100 ,
}));
Run Code Online (Sandbox Code Playgroud)
小智 14
我最近使用fabric.js构建了一个思维导图工具,我遇到了同样的问题.
为了实现您所描述的内容(在画布中创建文本元素之后和之后更改文本),我使用jquery来检测keydown事件.假设您在结构画布中选择了所需的文本元素,则以下代码段将更改文本.
$(document).keydown(function(e){
var keyPressed = String.fromCharCode(e.which);
var text = canvas.getActiveObject();
if (text)
{
var newText = '';
var stillTyping = true;
if (e.which == 27) //esc
{
if (!text.originalText) return; //if there is no original text, there is nothing to undo
newText = text.originalText;
stillTyping = false;
}
//if the user wants to make a correction
else
{
//Store the original text before beginning to type
if (!text.originalText)
{
text.originalText = text.text;
}
//if the user wants to remove all text, or the element entirely
if (e.which == 46) //delete
{
activeObject.element.remove(true);
return;
}
else if (e.which == 16) { //shift
newText = text.text;
}
else if (e.which == 8) //backspace
{
e.preventDefault();
newText = text.text.substr(0, text.text.length - 1);
}
else if (e.which == 13) //enter
{
//canvas clear selection
canvas.discardActiveObject();
canvas.renderAll();
canvasBeforeSelectionCleared({ memo: { target: text} });
newText = text.text;
stillTyping = false;
}
//if the user is typing alphanumeric characters
else if (
(e.which > 64 && e.which < 91) || //A-Z
(e.which > 47 && e.which < 58) || //0-9
(e.which == 32) || //Space
(keyPressed.match(/[!&()"'?-]/)) //Accepted special characters
)
{
if (text.text == text.originalText) text.text = '';
if (keyPressed.match(/[A-Z]/) && !e.shiftKey)
keyPressed = keyPressed.toLowerCase();
newText = text.text + keyPressed;
}
}
text.set({ text: newText }); //Change the text
canvas.renderAll(); //Update the canvas
if (!stillTyping)
{
this.text.originalText = null;
}
}
});
Run Code Online (Sandbox Code Playgroud)
使用这种技术,我可以在结构画布中选择一个文本元素,开始键入并替换文本.您可以更改它,以便每次选择元素时都不会删除文本.
这种方法有一些妥协.例如,您不能像在常规HTML输入文本元素中那样选择文本,并且没有闪烁的光标,因此"虚拟"光标始终位于文本的末尾.
如果你真的想要,你可以在文本末尾画一个闪烁的光标.