如何在FabricJS中获取当前选择的上一个和下一个单词?

时间:2017-11-17 23:07:36

标签: fabricjs

我想知道如何在FabricJS的Textbox元素中找到上一个和下一个单词。 假设我有下一个文本:

  

你好美好的世界。

目前,我的光标位于“漂亮”,所以我希望将“ Hello ”作为之前的文字和“世界”作为后面的文字。

有什么想法吗? TNX

http://jsfiddle.net/redlive/gdyvfj1h/1/

////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////

function getBeforeAndAfter(text){
	const start = text.selectionStart;
	const end = text.selectionEnd;
	const textBefore = '';
	const textAfter = '';
	///////////// THIS LOGIC NEEDS TO BE DEVELOPED HERE /////
	$('#before').val( textBefore );
	$('#after').val( textAfter );
}

////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
var canvas = new fabric.Canvas('paper');
canvas.setHeight(300);
canvas.setWidth(500);

var text = new fabric.Textbox('Hello beautiful world', {
  left: 50,
  top: 10,
  fontFamily: 'arial',
  fill: '#333',
  fontSize: 50
});
text.selectionStart = 6;
text.selectionEnd = 15;
canvas.add(text);
canvas.renderAll();


$("#btn").on("click", function(t){
	getBeforeAndAfter(text);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.19/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="paper" width="400" height="400" style="border:1px solid #ccc"></canvas>
Text before:
<input type="text" id="before" disabled/>
<br>
Text after:
<input type="text" id="after" disabled/>
<br>
<button id="btn">Get Before and After</button>

2 个答案:

答案 0 :(得分:0)

getBeforeAndAfter功能中,执行以下操作:

逻辑

首先,通过调用文本框的currentWord属性中的.slice,将当前选定的字词设置为字符串中的.text。提供startend作为您的参数。您现在拥有所选单词(&#39;漂亮&#39;)。

其次,split字符串由一个空格组成。

第三,找到indexOf您选择的单词(1)。

最后,您之前单词的内容为words[currentWordIndex - 1],您的下一个单词的内容为words[currentWordIndex + 1]

实施例

function getBeforeAndAfter(text){
    const string = text.text;
    const start = text.selectionStart;
    const end = text.selectionEnd;
    const currentWord = string.slice(start, end);

    const words = string.split(" ");
    const index = words.indexOf(currentWord);

    const textBefore = words[index-1];
    const textAfter = words[index+1];

    $('#before').val( textBefore );
    $('#after').val( textAfter );
}

答案 1 :(得分:0)

function getBeforeAndAfter(text){
    const start = text.selectionStart;
    const end = text.selectionEnd;

    text.selectionStart = text.findWordBoundaryLeft( start - 1 );
    text.selectionEnd = start;
    const textBefore = text.getSelectedText();

    text.selectionStart = end;
    text.selectionEnd = text.findWordBoundaryRight( end + 1 );
    const textAfter = text.getSelectedText();

    $('#before').val( textBefore );
    $('#after').val( textAfter );
}

工作版本在这里 http://jsfiddle.net/redlive/gdyvfj1h/6/