Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all text in a bounding rectangle

I made a region selector tool which makes a rectangle on the screen and gives the coordinates (top, left, width and height). Basically I want to get all (and only) visible text inside that rectangle. Also it should be the exact text, no repetitions.

This is how I make the region:

enter image description here

I'm trying something like this:

            var top = parseInt($('#selectionn33').css('top')) 
            var left = parseInt($('#selectionn33').css('left')) 
            var width = parseInt($('#selectionn33').css('width')) 
            var height = parseInt($('#selectionn33').css('height')) 

            var items = document.getElementsByTagName("*");
            for (var i = items.length; i--;) 
            {
                var rect = items[i].getBoundingClientRect();
                if(rect.top >= top && rect.top <= (top + height))
                {
                    if(rect.left >= left && rect.left <= (left + width))
                    {
                        console.log(items[i].textContent);
                    }
                }
            }

But it gets a lot of text I don't want, like text that is from an element that meets the criteria but is outside the rectangle.

Any ideas how I can make this?

like image 446
madprops Avatar asked Jul 07 '16 00:07

madprops


1 Answers

You should be able to get elements that are entirely inside the selection, as described in your comment, with very little changes to your code. Basically you are getting elements which have the top left corner within the selection. You need to make sure the bottom right corner is also inside the selection:

var $selection = $('#selection33');
var top = parseInt($selection.css('top')); 
var left = parseInt($selection.css('left')); 
var right = left + parseInt($selection.css('width')); 
var bottom = top + parseInt($selection.css('height')); 

var items = document.getElementsByTagName("*");
for (var i = items.length - 1; i >= 0; i--) {
  var rect = items[i].getBoundingClientRect();
  if(
    rect.top >= top && rect.bottom <= bottom &&
    rect.left >= left && rect.right <= right
  ) {
       try
       {
           found = items[i].childNodes[0].nodeValue;
       }
           catch(err)
       {
           found = items[i].textContent;
       }
  }
}
like image 103
Hugo Silva Avatar answered Sep 18 '22 13:09

Hugo Silva