fabric.js中删除文本内容时不删除画布对应文本框的实现方法
问题根因
你的deleteText方法的else分支逻辑错误:当用户没有选中文本区间(startIndex == endIndex)时,直接调用了canvas.remove删除了整个文本框控件,同时也没有处理光标在非开头位置按删除键删单个字符的场景。
修复方案
修改deleteText方法,所有场景下仅修改文本内容,移除删除控件的逻辑即可:
deleteText(activeObject) { var startIndex = activeObject.selectionStart; var endIndex = activeObject.selectionEnd; var text = activeObject.text; var newText = ''; if (startIndex != endIndex) { // 选中多字符删除场景 newText = text.substring(0, startIndex) + text.substring(endIndex, text.length); } else if (startIndex > 0) { // 无选中文本,删除光标前单个字符场景 newText = text.substring(0, startIndex - 1) + text.substring(startIndex, text.length); } else { // 光标在文本最开头,按删除键直接清空内容 newText = ''; } activeObject.set("text", newText); this.canvas.fire("object:modified"); // 如果你后续需要加空文本自动删除控件的逻辑,可放开下面的注释 // if (newText === '') { // this.canvas.remove(activeObject); // } }
额外说明
原有代码中的text.substring(endIndex + 1, text.length)逻辑也存在问题,会导致删除选中区间时多跳过一个字符,修复方案中已修正为endIndex。
内容的提问来源于stack exchange,提问作者kashyap
相关产品推荐
相关产品推荐

