Previous and Next words
FabricJS
by Eugene Vilder
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.19/fabric.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>
JavaScript
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
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 );
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
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();
getBeforeAndAfter(text);
$("#btn").on("click", function(t){
getBeforeAndAfter(text);
});