如何提取选区并显示区域的大小

时间:2019-03-29 08:00:23

标签: javascript jquery node.js user-interface

enter image description here

要使鼠标能够拉出选择范围,请在选择后释放鼠标并显示widthheight的{​​{1}}和X-axis的值在这四个字段中选择的区域。

这是我的问题。我希望你能帮助我。谢谢。

1 个答案:

答案 0 :(得分:0)

我为可能的解决方案之一创建了小码笔,您需要根据情况进行调整。

Coepen Select Area

let isDragging = false;
const startArr=[];
document.getElementById('target_element').addEventListener('mousedown', function(e){
  startArr[0] = e.offsetX;
  startArr[1] = e.offsetY;
  isDragging=true
})

const currentArr=[]
document.getElementById('target_element').addEventListener('mousemove', function(e){
  if (isDragging){
    currentArr[0] = e.offsetX;
    currentArr[1] = e.offsetY;

    const dimensions = getDimensions(startArr, currentArr);
    const parentElement = document.getElementById('target_element');
    parentElement.innerHTML = '';
    const selectWindow = document.createElement('div');
    selectWindow.style.position = 'absolute';
    selectWindow.style.height = dimensions.h+'px';
    selectWindow.style.width = dimensions.w+'px';
    selectWindow.style.top = dimensions.y+'px';
    selectWindow.style.left = dimensions.x+'px';
    selectWindow.style.backgroundColor = 'blue';
    parentElement.appendChild(selectWindow);
    currentArr.length = 0;
  }
})
const finishArr=[];
document.getElementById('target_element').addEventListener('mouseup', function(e){
  if (isDragging){
    finishArr[0] = e.offsetX;
    finishArr[1] = e.offsetY;

    const dimensions = getDimensions(startArr, finishArr);
    document.getElementById('x').innerText = dimensions.x;
    document.getElementById('y').innerText = dimensions.y;
    document.getElementById('w').innerText = dimensions.w;
    document.getElementById('h').innerText = dimensions.h;
    isDragging=false;
  }
})
function getDimensions(startingPoint, finishPoint){
  const top = Math.min(startingPoint[1], finishPoint[1]);
  const bottom = Math.max(startingPoint[1], finishPoint[1]);
  const left = Math.min(startingPoint[0], finishPoint[0]);
  const right = Math.max(startingPoint[0], finishPoint[0]);
  return {
    x: left,
    y: top,
    w: right-left,
    h: bottom-top
  }
}