Javascript - Track mouse position

后端 未结 11 1297
谎友^
谎友^ 2020-11-22 03:13

I am hoping to track the position of the mouse cursor, periodically every t mseconds. So essentially, when a page loads - this tracker should start and for (say) every 100 m

相关标签:
11条回答
  • 2020-11-22 04:02
    onmousemove = function(e){console.log("mouse location:", e.clientX, e.clientY)}
    

    Open your console (Ctrl+Shift+J), copy-paste the code above and move your mouse on browser window.

    0 讨论(0)
  • 2020-11-22 04:03

    ES6 based code:

    let handleMousemove = (event) => {
      console.log(`mouse position: ${event.x}:${event.y}`);
    };
    
    document.addEventListener('mousemove', handleMousemove);
    

    If you need throttling for mousemoving, use this:

    let handleMousemove = (event) => {
      console.warn(`${event.x}:${event.y}\n`);
    };
    
    let throttle = (func, delay) => {
      let prev = Date.now() - delay;
      return (...args) => {
        let current = Date.now();
        if (current - prev >= delay) {
          prev = current;
          func.apply(null, args);
        }
      }
    };
    
    // let's handle mousemoving every 500ms only
    document.addEventListener('mousemove', throttle(handleMousemove, 500));
    

    here is example

    0 讨论(0)
  • 2020-11-22 04:06

    If just want to track the mouse movement visually:

    <!DOCTYPE html>
    <html>
    <head>
    <title></title>
    </head>
    <style type="text/css">
    * { margin: 0; padding: 0; }
    html, body { width: 100%; height: 100%; overflow: hidden; }
    </style>
    <body>
    <canvas></canvas>
    
    <script type="text/javascript">
    var
    canvas    = document.querySelector('canvas'),
    ctx       = canvas.getContext('2d'),
    beginPath = false;
    
    canvas.width  = window.innerWidth;
    canvas.height = window.innerHeight;
    
    document.body.addEventListener('mousemove', function (event) {
    	var x = event.clientX, y = event.clientY;
    
    	if (beginPath) {
    		ctx.lineTo(x, y);
    		ctx.stroke();
    	} else {
    		ctx.beginPath();
    		ctx.moveTo(x, y);
    		beginPath = true;
    	}
    }, false);
    </script>
    </body>
    </html>

    0 讨论(0)
  • 2020-11-22 04:08

    I don't have enough reputation to post a comment reply, but took TJ Crowder's excellent answer and fully defined the code on a 100ms timer. (He left some details to the imagination.)

    Thanks OP for the question, and TJ for the answer! You're both a great help. Code is embedded below as a mirror of isbin.

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Example</title>
      <style>
        body {
          height: 3000px;
        }
        .dot {
          width: 2px;
          height: 2px;
          background-color: black;
          position: absolute;
        }
      </style>
    </head>
    <body>
    <script>
    (function() {
        "use strict";
        var mousePos;
    
        document.onmousemove = handleMouseMove;
        setInterval(getMousePosition, 100); // setInterval repeats every X ms
    
        function handleMouseMove(event) {
            var eventDoc, doc, body;
    
            event = event || window.event; // IE-ism
    
            // If pageX/Y aren't available and clientX/Y are,
            // calculate pageX/Y - logic taken from jQuery.
            // (This is to support old IE)
            if (event.pageX == null && event.clientX != null) {
                eventDoc = (event.target && event.target.ownerDocument) || document;
                doc = eventDoc.documentElement;
                body = eventDoc.body;
    
                event.pageX = event.clientX +
                  (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
                  (doc && doc.clientLeft || body && body.clientLeft || 0);
                event.pageY = event.clientY +
                  (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
                  (doc && doc.clientTop  || body && body.clientTop  || 0 );
            }
    
            mousePos = {
                x: event.pageX,
                y: event.pageY
            };
        }
        function getMousePosition() {
            var pos = mousePos;
    		
            if (!pos) {
                // We haven't seen any movement yet, so don't add a duplicate dot 
            }
            else {
                // Use pos.x and pos.y
                // Add a dot to follow the cursor
                var dot;
                dot = document.createElement('div');
                dot.className = "dot";
                dot.style.left = pos.x + "px";
                dot.style.top = pos.y + "px";
                document.body.appendChild(dot);
            }
        }
    })();
    </script>
    </body>
    </html>

    0 讨论(0)
  • 2020-11-22 04:09

    Irrespective of the browser, below lines worked for me to fetch correct mouse position.

    event.clientX - event.currentTarget.getBoundingClientRect().left event.clientY - event.currentTarget.getBoundingClientRect().top

    0 讨论(0)
提交回复
热议问题