绘制水平和垂直线在鼠标位置折叠

时间:2016-03-16 15:13:41

标签: javascript

我想在鼠标位置绘制水平和垂直线折叠。我面临两个问题

  1. 水平线未显示。看起来像一些CSS问题,但无法弄清楚。
  2. 移动鼠标时,重绘线条不平滑。它的混乱。无论如何我可以避免这种情况吗?
  3. fiddle

    代码:

    var element = document.getElementById('box');
    
    var drawLines = function(event) {
      var x = event.pageX;
      var y = event.pageY;
    
      var straightLine = element.querySelector('.straightLine');
      var hrLine = element.querySelector('.hrLine');
    
      var slTrans = 'translate(' + x + 'px, 0px)';
      var hrTrans = 'translate(0px, ' + y + 'px)';
      if(!straightLine) {
         straightLine = document.createElement('div');
         straightLine.classList.add('straightLine');
         straightLine.style.height = "100%";
         straightLine.style.width = '2px';
         element.appendChild(straightLine);
      }
      straightLine.style.transform = slTrans;
    
      if(!hrLine) {
         hrLine = document.createElement('div');
         hrLine.style.height = "2px";
         hrLine.classList.add('hrLine');
         hrLine.style.width = '100%';
         element.appendChild(hrLine);
      }
      hrLine.style.transform = hrTrans;
    }
    
    element.addEventListener('mousemove', function(event) {
       drawLines(event);
    });
    
    element.addEventListener('mousedown', function(event) {
       drawLines(event);   
    });
    
    element.addEventListener('mouseup', function(event) {
       drawLines(event);
    });
    
    element.addEventListener('mouseout', function(event) {
       drawLines(event);
    });
    

1 个答案:

答案 0 :(得分:3)

水平线问题可以通过以下方式解决:

.straightLine, .hrLine {
    position: absolute;
    background-color: red;
}

查看更新的fiddle

修改
您还可以使用以下内容来平滑动画(您必须根据自己的需要调整时间跨度:

.straightLine, .hrLine {
    position: absolute;
    background-color: red;
    transition: transform .05s ease-in-out;
}

查看更新的fiddlew3schools.com