Created
March 20, 2017 12:13
-
-
Save Pawan-Bishnoi/84df5df593ddbda1cdf12aaeeed9cb23 to your computer and use it in GitHub Desktop.
Emulating text tool with paperjs pointText and an HTML textarea element
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Add an textarea, this is to be used as 'the editor' | |
* We will place it over some pointText that we want to edit | |
**/ | |
var $anchor = $('body'); | |
$anchor.append ('<textarea class="text-box" maxlength="50"' + | |
' style="position: absolute; color: black; display:none" type="text">' + | |
'</textarea>'); // hidden initially | |
var editor = $anchor.find ('.text-box'); | |
/** | |
* On mouse down: | |
* - Select if some text is hit | |
* - Unselect any prev selected text if hitresult is null | |
* - else place a new text | |
**/ | |
function mouse_down (ev) { | |
/* | |
* If click hits some text box then mark it focused */ | |
var item = text_hit_test (ev.point); | |
if (item) { | |
if (active_box) | |
set_box_active (false); | |
active_box = item; | |
set_box_active (true); | |
return ; | |
} | |
/* | |
* If some text box is focused then unfocus it */ | |
if (active_box) { | |
set_box_active (false); | |
active_box = null; | |
return ; | |
} | |
/* | |
* Otherwise create one and mark it focused */ | |
create (ev.point, true); | |
} | |
/** | |
* Hit test | |
**/ | |
function text_hit_test (point) { | |
var items = paper.project.getItems ({ | |
class: paper.scope.PointText | |
}); | |
for (var i=0; i < items.length; i++) { | |
var item = items [i]; | |
if (item.contains (point)) { | |
return item; | |
} | |
} | |
return null; | |
} | |
/** | |
* Set box active (true/false) | |
**/ | |
function set_box_active (val) { | |
paper.project.activeLayer.selected = false; | |
if (!active_box) | |
return; | |
show_textbox.call (val, active_box.bounds.topLeft); | |
paper.scope.view.update(); | |
} | |
/** | |
* Show/hide 'the editor' | |
**/ | |
function show_textbox (val, point) { | |
if (!val) { | |
active_box.content = box.val(); | |
active_box.visible = true; | |
editor.val(''); | |
editor.css ('display', 'none'); | |
} | |
else { | |
var pos = paper.scope.view.projectToView (point); | |
editor.val (active_box.content); | |
active_box.visible = false; | |
editor.css ('display', 'block'); | |
editor.css ({top: pos.y, left: pos.x}); | |
editor.focus (); | |
} | |
} | |
/** | |
* @NOTE: This code is extracted from a bigger file. | |
* I may have missed something, please let me know of any confusion/doubt | |
**/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment