jQuery Javascript image magnifier

sadmicrowave picture sadmicrowave · May 20, 2011 · Viewed 8.2k times · Source

I'm looking for a jquery or javascript image magnifier on hover that does not require two images ( large and small ) to work. I've searched for hours and haven't found any that work the way they are said to.

  • iZoom,
  • jQZoom,
  • tjpZoom,
  • Image Magnify,
  • ImageZoom,
  • ImageLens,
  • Loupe

have all been tried and don't work for one reason or another with my current config.

So at this point I'm looking for non-googled results since I've gone through 25 pages of results from 'jquery Image Magnifier' and nothing has worked.

Answer

oyophant picture oyophant · Aug 20, 2013

You could render a duplicate of the image in a hidden canvas, grab a rectangle around the mouse position and render a magnification of this part in a second visible canvas. It is written in very few lines of code - even in plain Javascript:

var zoom = function(img){
    var canS = document.createElement('canvas'),
        can = document.createElement('canvas'),
        ctxS = canS.getContext('2d'),
        ctx = can.getContext('2d'),
        id = ctx.createImageData(240,240),
        de = document.documentElement;
    can.className = 'zoom';
    can.width = can.height = 240;
    canS.width = img.width;
    canS.height = img.height;
    img.parentElement.insertBefore(can,img.nextSibling);
    ctxS.drawImage(img,0,0);
    img.onmousemove = function(e){
        var idS=ctxS.getImageData(
            e.clientX-e.target.offsetLeft+(window.pageXOffset||de.scrollLeft)-20,
            e.clientY-e.target.offsetTop+(window.pageYOffset||de.scrollTop)-20,
            40,40);
        for (var y=0;y<240;y++)
            for (var x=0;x<240;x++)
                for (var i=0;i<4;i++)
                    id.data[(240*y+x)*4+i] = idS.data[(40*~~(y/6)+~~(x/6))*4+i];
        ctx.putImageData(id,0,0);
    }
}

Example: http://kirox.de/test/magnify.html

There's a link to an improved version featuring an adjustable round lens with light effects and barrel distortion. Also works with canvases.

Restrictions:

  • does not work with cross domain image URLs
  • does not work in older versions of IE
  • in the current version of Firefox 25 there is a significant slowdown after a while of hovering