Here’s a starting point to do this with native Javascript.
It is not difficult, my example may need some adjustments but so you learn better also how it works.
Basically you need to control some parameters:
- know when and where the mouse clicks on the image to start dragging
- know where mouse moves and cancel native drag
- change the width of the selection as it drags
- add the event headphone
mousemove
to the window, to know when to drag it out
- use the
getBoundingClientRect
to know the positions of the corners of the selection
These steps are in the code below, this could be in practice:
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>
In the example the results are
- "upper right corner" as
se
- "upper left corner" as
sd
- etc.
If you have any questions say I’ll explain it better.
This square comes from where? is a div that you drag to that position or is a part of the image?
– Sergio
So @Sergio, it comes from a part of the image. The idea would be to select any part of the image with a "select area" equal to the selects of Crop, only then instead of doing Crop, it would return the indicated points.
– gelopes
I don’t understand yet... you say it comes from a part of the image, but the idea would be to select any part of the image. The red rectangle is part of the
jpg
,png
or was created in the browser with user interaction?– Sergio
Created in the browser with user interaction. I ended up finding a practical use in the Cropper plugin. Take a look link - X, Y, Width, Width, which is the information I need.
– gelopes