在javascript中使box边缘跟随鼠标指针

making box edge follow mouse pointer in javascript

本文关键字:跟随 鼠标指针 边缘 box javascript 中使      更新时间:2023-09-26

我不明白为什么这不起作用。我这里有一个DIV制作的黑色画布。在这个画布上,我希望用户定义我成功的第一个点,但在单击第一个点后,当鼠标移动时,框的大小必须正确,并跟随鼠标,就像在绘图程序中绘制矩形框一样。这是我遇到困难的地方。

有没有一种方法可以解决这个问题,使其在不使用Jquery的情况下最低限度地工作?如果我能为InternetExplorer7(或至少8)找到一个解决方案,那就更好了。

<div ID="CANVAS" style="background:#000;width:600px;height:400px"></div>
<script>
var startx=-1,starty=-1,points=0,box;
var canvas=document.getElementById('CANVAS');
canvas.onclick=dopoint;
canvas.onmousemove=sizebox;
function dopoint(e){
  if (points==0){
    var area=canvas.getBoundingClientRect();
    box=document.createElement('DIV');
    box.style.position='relative';
    box.style.border='2px solid yellow';
    canvas.appendChild(box);
    startx=e.clientX-area.left;
    starty=e.clientY-area.top;
    box.style.left=startx+'px';
    box.style.top=starty+'px';
    box.style.width='10px';
    box.style.height='10px';
  }
  points=1-points;
}
function sizebox(e){
  if (points==1){
    var x=e.clientY,y=e.clientY; //here I'm thinking subtract old point from new point to get distance (for width and height)
    if (x>startx){
      box.style.left=startx+'px';
      box.style.width=(x-startx)+'px';
    }else{
      box.style.left=x+'px';
      box.style.width=(startx-x)+'px';
    }
    if (y>starty){
      box.style.top=starty+'px';
      box.style.height=(y-starty)+'px';
    }else{
      box.style.top=y+'px';
      box.style.height=(starty-y)+'px';
    }
  }
}
</script>

您的代码几乎很好,除了一些小事情。我已经更正了它,并在我更改的行上写了一些评论。

https://jsfiddle.net/1brz1gpL/3/

var startx=-1,starty=-1,points=0,box;
var canvas=document.getElementById('CANVAS');
canvas.onclick=dopoint;
canvas.onmousemove=sizebox;
function dopoint(e){
  if (points==0){
    var area=canvas.getBoundingClientRect();
    box=document.createElement('DIV');
    box.style.position='absolute'; // here was relative and changed to absolute
    box.style.border='2px solid yellow';
    canvas.appendChild(box);
    startx=e.clientX; // removed -area.left
    starty=e.clientY; // removed -area.right
    box.style.left=startx+'px';
    box.style.top=starty+'px';
    box.style.width='0px'; // updated to 0px instead of 10 so it won't "jump" after you move the mouse with less then 10px
    box.style.height='0px'; // same
  }
  points=1-points;
}
function sizebox(e){
  if (points==1){
    var x=e.clientX,y=e.clientY; // here was x = e.clientY and changed to x = clientX
    if (x>=startx){
      box.style.left=startx+'px';
      box.style.width=(x-startx)+'px'; // here it was x+startx and changed to x-startx
    }else{
      box.style.left=x+'px';
      box.style.width=(startx-x)+'px';
    }
    if (y>starty){
      box.style.top=starty+'px';
      box.style.height=(y-starty)+'px';
    }else{
      box.style.top=y+'px';
      box.style.height=(starty-y)+'px';
    }
  }
}