JavaScript Image zoom with CSS3 Transforms, How to calculate Origin? (with example)

不打扰是莪最后的温柔 提交于 2020-01-01 11:58:07

问题


I'm trying to implement an image zoom effect, a bit like how the zoom works with Google Maps, but with a grid of fix position images.

I've uploaded an example of what I have so far here:

http://www.dominicpettifer.co.uk/Files/MosaicZoom.html

(uses CSS3 transforms so only works with Firefox, Opera, Chrome or Safari)

Use your mouse wheel to zoom in/out. The HTML source is basically an outer div with an inner-div, and that inner-div contains 16 images arranged using absolute position. It's going to be a Photo Mosaic basically.

I've got the zoom bit working using CSS3 transforms:

$(this).find('div').css('-moz-transform', 'scale(' + scale + ')');

...however, I'm relying on the mouse X/Y position on the outer div to zoom in on where the mouse cursor is, similar to how Google Maps functions. The problem is that if you zoom right in on an image, move the cursor to the bottom/left corner and zoom again, instead of zooming to the bottom/left corner of the image, it zooms to the bottom/left of the entire mosaic. This has the effect of appearing to jump about the mosaic as you zoom in closer while moving the mouse around, even slightly.

That's basically the problem, I want the zoom to work exactly like Google Maps where it zooms exactly to where your mouse cursor position is, but I can't get my head around the Maths to calculate the transform-origin: X/Y values correctly. Please help, been stuck on this for 3 days now.

Here is the full code listing for the mouse wheel event:

var scale = 1;

$("#mosaicContainer").mousewheel(function(e, delta)
{
    if (delta > 0)
    {
        scale += 1;
    }
    else
    {
        scale -= 1;
    }
    scale = scale < 1 ? 1 : (scale > 40 ? 40 : scale);

    var x = e.pageX - $(this).offset().left;
    var y = e.pageY - $(this).offset().top;

    $(this).find('div').css('-moz-transform', 'scale(' + scale + ')')
        .css('-moz-transform-origin', x + 'px ' + y + 'px');

    return false;
});

回答1:


Finally figured it out, check it out here:

http://www.dominicpettifer.co.uk/Files/Mosaic/MosaicTest.html

Use the mouse wheel to zoom, you can also drag the image about, only works properly on latest Safari, Opera and Firefox (images are blurry on Chrome for some reason). Also a bit buggy in certain areas. Got a lot of help someone at DocType http://doctype.com/javascript-image-zoom-css3-transforms-calculate-origin-example



来源:https://stackoverflow.com/questions/2823513/javascript-image-zoom-with-css3-transforms-how-to-calculate-origin-with-examp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!