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

making box edge follow mouse pointer in javascript

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

有没有一种方法可以解决这个问题,使其至少可以正常工作并且不使用 Jquery?如果我能得到适用于 Internet Explorer 7(或至少 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';
    }
  }
}