Core JavaScript

An Image with a Magnifying Glass

This JavaScript Reference section displays the code for an example program that shows how create a magnifying glass for an image in JavaScript.

MagnifyingGlass.html

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net's Javascript</title>
    <script type="text/javascript" src="MagnifyingGlass.js"></script>
  </head>
  <body>
    <div style="box-sizing: border-box; position:relative;margin:100px;">
      <img id="idImage" style="box-sizing: border-box;"
        src="ChristHealingTheSick_CarlHeinrichBloch.jpg" width="600" height="478">
    </div>
    <script>
      Initialize();
    </script>
  </body>
</html>

MagnifyingGlass.js

var gqIm = null;
var gqMG = null;

function Initialize() {
  gqIm = document.getElementById("idImage");
  gqMG = CreateMagnifyingGlass();
  gqIm.addEventListener("mousemove", MoveMG);
  gqMG.addEventListener("mousemove", MoveMG);
}

function CreateMagnifyingGlass() {
  var qMG = document.createElement("div");
  gqIm.parentElement.insertBefore(qMG, gqIm);
  qMG.style.position = "absolute";
  var iBorderWidth = 2;
  qMG.style.border = iBorderWidth + "px black solid";
  qMG.style.borderRadius = "50%";
  qMG.style.cursor = "none";
  // Set the size of the magnifying glass
  qMG.style.width = "200px";
  qMG.style.height = "200px";
  qMG.bw = iBorderWidth;
  qMG.w = qMG.offsetWidth / 2;
  qMG.h = qMG.offsetHeight / 2;
  // Set the magnification level: 5 = 5 times
  qMG.mag = 5;
  qMG.style.boxSizing = "border-box";
    qMG.style.backgroundImage = "url('" + gqIm.src + "')";
    qMG.style.backgroundRepeat = "no-repeat";
  qMG.style.backgroundSize = (gqIm.width * qMG.mag) + "px " + (gqIm.height * qMG.mag) + "px";
  qMG.style.display = 'none';
  return qMG;
}

function MoveMG(e) {
  gqMG.style.display = 'block';
  // Suppress other actions
  e.preventDefault();
  var qP = getCursorPos(e);
  // Check whenther the magnifying glass is outside the image
  if (qP.x > gqIm.width - (gqMG.w / gqMG.mag)) {gqMG.style.display = 'none';}
  if (qP.x <  gqMG.w / gqMG.mag) {gqMG.style.display = 'none';}
  if (qP.y > gqIm.height - ( gqMG.h / gqMG.mag)) {gqMG.style.display = 'none';}
  if (qP.y <  gqMG.h / gqMG.mag) {gqMG.style.display = 'none';}
  // Set the position of the magnifying glass
  gqMG.style.left = (qP.x - gqMG.w) + "px";
  gqMG.style.top = (qP.y - gqMG.h) + "px";
  // Set the visible portion of the image
  gqMG.style.backgroundPosition =
    "-" + ((qP.x * gqMG.mag) - gqMG.w + gqMG.bw) + "px " +
    "-" + ((qP.y * gqMG.mag) - gqMG.h + gqMG.bw) + "px";
}

function getCursorPos(e) {
  e = e || window.event;
  // Get the upper-left corner of the image
  var qUL = gqIm.getBoundingClientRect();
  // Get the cursor position within the image. Remove any page scrolling.
  var dCurX = e.pageX - qUL.left - window.pageXOffset;
  var dCurY = e.pageY - qUL.top - window.pageYOffset;
  return {x : dCurX, y : dCurY};
}
 

Output

 
 

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