Coordinates of selected area in image

6

I have the following question:

I have an image and I want to make a selection of any area of this image, as in the example marked by the red square (consider this to be the selection).

From this selection, I need to know the coordinate of each of the points, for example in the image: Point 01 = XY coordinate | Item 02 .....

Can anyone give me an idea how I can do this?

    
asked by anonymous 12.06.2016 / 19:05

2 answers

2

Here is a starting point for doing this with native JavaScript.

It's not difficult, my example may need some tweaking, but you'll also learn better how it works.

You basically need to control some parameters:

  • know when and where the mouse clicks on the image to start dragging
  • know where the mouse moves and cancel the native drag
  • change the width of the selection as you drag
  • add the event handler from mousemove to window, to find out when the drag is finished
  • use getBoundingClientRect to know the corners of the selection

These steps are in the code below, this could in practice look like this:

JavaScript:

var info = document.getElementById('info');
var img = document.querySelector('img');
var selecao = document.getElementById('selecao');

var inicio;

function arrastador(e) {
    e.preventDefault();
    selecao.style.width = e.pageX - inicio.x + 'px';
    selecao.style.height = e.pageY - inicio.y + 'px';
    gerarInfo();
}

function gerarInfo() {
    var pos = selecao.getBoundingClientRect();
    var coords = {
        se: [pos.left, pos.top],
        sd: [pos.right, pos.top],
        ie: [pos.left, pos.bottom],
        id: [pos.right, pos.bottom]
    };
    info.innerHTML = JSON.stringify(coords);
}
img.addEventListener('mousedown', function(e) {
    inicio = {
        x: e.pageX,
        y: e.pageY
    };
    selecao.style.display = 'block';
    selecao.style.left = inicio.x + 'px';
    selecao.style.top = inicio.y + 'px';
    selecao.style.width = 0;
    selecao.style.height = 0;
    window.addEventListener('mousemove', arrastador);
});
window.addEventListener('mouseup', function(e) {
    inicio = null;
    window.removeEventListener('mousemove', arrastador);
    gerarInfo();
});

CSS:

#selecao {
    border: 2px #aaf solid;
    position: absolute;
    display: none;
    background-color: rgba(255, 0, 0, 0.3);
}

HTML:

<div id="info">Aqui vai aparecer info...</div>
<img src="http://images6.mygola.com/518e281853db45a2b7fe72a008e3b54a_1394089229_l.jpg"alt="" />
<div id="selecao"></div>

jsFiddle: link

In the example the results are

  • "upper right corner" as se
  • "upper left corner" as sd
  • etc

If you have any questions, please let me explain.

    
13.06.2016 / 16:51
1

I found a practical solution in the Cropper plugin. It returns exactly this information from the image. Selection made in the browser with user interaction. Returns the X, Y, Width and Height coordinates.

link

    
12.06.2016 / 20:22