简体   繁体   English

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

[英]Draw horizontal and vertical lines collapsing at mouse position

I am tying to draw horizontal and vertical line collapsing at mouse position.我想绘制在鼠标位置折叠的水平和垂直线。 I am facing two problems我面临两个问题

  1. Horizontal line is not showing up.水平线不显示。 Seems like some CSS issue but could not figure out.似乎是一些 CSS 问题,但无法弄清楚。
  2. While moving mouse the redrawing of lines is not smooth.移动鼠标时,线条的重绘不流畅。 Its cluttering.它的混乱。 Anyway I can avoid that?反正我能避免吗?

fiddle小提琴

Code:代码:

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);
});

The horizontal line issue can be fixed with:水平线问题可以通过以下方式解决:

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

See updated fiddle .请参阅更新的小提琴

EDIT编辑
You can also use the following to smooth out the animation (you'll have to adjust the timespan to suit your needs:您还可以使用以下内容来平滑动画(您必须调整时间跨度以满足您的需要:

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

See updated fiddle and w3schools.com .请参阅更新的小提琴w3schools.com

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM