Core JavaScript

SVG - Rotate to Mouse Cursor

The acronym SVG stands for Scalable Vector Graphics and refers to graphics that are generated by a geometric specification rather than by pixels, like an image (called rasterized graphics as opposed to the vectorized graphics described here).

RotateToMouseCursor.html

<!DOCTYPE html>
<html>
<head>
  <title>XoaX.net's HTML</title>
  <style>
    #idDiv {
      padding:10px;
      background-color:black;
      border: 1px solid white;
      float:left;
    }
  </style>
  <script type="text/javascript" src="RotateToMouseCursor.js"></script>
</head>
<body>
  <div id="idDiv">
    <svg width="600px" height="600px" xmlns="http://www.w3.org/2000/svg"
      viewBox="-300.0 -300.0 600 600">
      <defs>
        <g id="idArrowHead" transform="rotate(30)">
          <polygon points="-25 25 25 0 -25 -25 -15 0" fill="red" stroke="white"
            stroke-width="2"/>
        </g>
	  </defs>
      <use xlink:href="#idArrowHead" />
    </svg>
  </div>
</body>
</html>

RotateToMouseCursor.js

function Init() {
var qDivElement = document.getElementById("idDiv");
  // The mouse move event handler
  qDivElement.onmousemove = function(e) {
    this.SetCursorCoordinates(e);
    var dCenterX = (this.clientWidth + 1)/2;
    var dCenterY = (this.clientHeight + 1)/2;
    var dDeltaX = this.mdCursorX - dCenterX;
    var dDeltaY = this.mdCursorY - dCenterY;
    qGroupElement = document.getElementById("idArrowHead");
    var dAngle = ((Math.atan2(dDeltaY, dDeltaX)*180)/Math.PI);
    qGroupElement.setAttribute('transform', 'rotate('+dAngle+')');
  };
  // A function to calculate the coordinates of the cursor in the
  qDivElement.SetCursorCoordinates = function(e) {
    var dElementOffsetX = 0;
    var dElementOffsetY = 0;
    var qElement = this;
    do{
      dElementOffsetX += qElement.offsetLeft - qElement.scrollLeft;
      dElementOffsetY += qElement.offsetTop - qElement.scrollTop;
      qElement = qElement.offsetParent
    } while(qElement != document.body)
    this.mdCursorX = e.pageX - dElementOffsetX;
    this.mdCursorY = e.pageY - dElementOffsetY;
  }
}
var qGroupElement = null;
window.onload = Init;
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.