Search code examples
javascriptcursorcursor-positiononmousemove

Move cursor and display it in another place


I am learning JavaScript. And I have this task - to draw two rectangles, in one of them, I should move the cursor, and it should appear in the second rectangle. It is not that hard to track the cursor, bu I have no idea how to display it somewhere else. Do I need to create separate canvas? How to display cursor image? I would be very grateful for any tips!

Here is a simple code that I have for now:

<html>   
<body>
    <canvas id="myCanvas" width="800" height="600" ></canvas>
    <script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.rect(20, 20, 300, 200);
    ctx.stroke();

    ctx.rect(350, 20, 300, 200);
    ctx.stroke();

    var cursorX;
    var cursorY;
    document.onmousemove = function(e){
        cursorX = e.pageX;
        cursorY = e.pageY;
    }
    </script> 
</body>


Solution

  • You should create an IMG with a cursor in it. Then, when you are moussing over one rectangle, use the img's (or containing DIV's) css to display it over the second rectangle correctly. It is similar to how you might display a tooltip

    function (event) {
      var x = event.pageX;
      var y = event.pageY;
        var mouseImg = document.getElementById('mouseImg');
        if (mouseImg ) {
          $(mouseImg ).css('left',(x + rectangleOffset.x) + 'px');
          $(mouseImg ).css('top',y + rectangleOffset.y + 'px');
          $(mouseImg ).show();
        }
      }