繁体   English   中英

动画元素到鼠标光标

[英]Animating element to mouse cursor

我必须将我在onmousedown上创建的元素移动到onmouseup光标的方向并为整个事物设置动画。

/*
function to spawn the ball
@param {event} event: onclick event
*/

var isDown = false;
var isDrag = false;

/*
function to get the position of the cursor on mouse down
@param {mousedown} event
*/
document.body.onmousedown = function (mousedown) {
  downX = mousedown.offsetX;
  downY = mousedown.offsetY;
  isDraggring = true;

  /*
  function to check if the user is dragging or clicking
  */
  document.body.onmousemove = function () {
    if (isDraggring) isDrag = true;

    /*
    function to detect the the mouse up event
    @param {mouseup} event
    */
    document.body.onmouseup = function (mouseup) {
      if (isDrag) {
        var ball = document.createElement("p");
        ball.innerHTML = "ball";
        document.body.append(ball);
        ball.style.position = "absolute";
        ball.style.left = downX - ball.offsetWidth / 2 + "px";
        ball.style.top = downY - ball.offsetHeight / 2 + "px";
      }
    };
  };
};

如果位置在相同的高度并且没有角度,那就是:ball.style.left/top=mouseup.offsetX/Y 但因为大多数时候都有一个小角度的事件我不知道如何使“球”向那个方向移动。 此外,球在到达光标后不应停止。 有什么帮助吗?

我采用了最简单的方法,只需保存mouse-up事件坐标,然后将球带到那里。

如果您需要继续这个动画:您已经获得了mouse-downmouse-up事件坐标,您可以计算这些点之间的斜率,并且您将知道您想要前进的方向。

 /* function to spawn the ball @param {event} event: onclick event */ var isDown = false; var isDrag = false; /* function to get the position of the cursor on mouse down @param {mousedown} event */ document.body.onmousedown = function (mousedown) { downX = mousedown.offsetX; downY = mousedown.offsetY; isDraggring = true; /* function to check if the user is dragging or clicking */ document.body.onmousemove = function () { if (isDraggring) isDrag = true; /* function to detect the the mouse up event @param {mouseup} event */ document.body.onmouseup = function (mouseup) { if (isDrag) { var ball = document.createElement("p"); ball.className = "ball"; ball.innerHTML = "ball"; document.body.append(ball); ball.style.position = "absolute"; ball.style.left = downX - ball.offsetWidth / 2 + "px"; ball.style.top = downY - ball.offsetHeight / 2 + "px"; setTimeout(()=>{ ball.style.left = mouseup.clientX + "px"; ball.style.top = mouseup.clientY + "px"; }, 500); } }; }; };
 body{ width: 100vw; height: 100vh; margin: 0; } .ball{ transition: 0.5s; }

暂无
暂无

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

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