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.