在缩放图像上获得正确的单击位置

时间:2015-11-29 08:28:42

标签: javascript jquery

这是我点击图像进行图像转换时获取点击位置的方法。但我的问题是,图像具有CSS属性max-width: 1000px。因此代码仅适用于较小的图像。对于较大的图像,位置结果不是点击的真实像素。

我的问题是,是否可以为自然大小的图像计算正确的点击位置。另一种方法是使用实​​际图像大小设置一些数据属性,如data-width: '1200px'data-height: '1000px'。但我还是要做一些计算。

parentPosition = getPosition(event.currentTarget),
x = event.clientX - parentPosition.x,
y = event.clientY - parentPosition.y;

function getPosition(element) {
    var xPosition = 0;
    var yPosition = 0;

    while (element) {
        xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
        yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
        element = element.offsetParent;
    }
    return { x: xPosition, y: yPosition };
}

2 个答案:

答案 0 :(得分:2)

If you know natural size and current size, i think you can just do this:

naturalClickPosX = (naturalWidth / currentWidth) * currentClickPosX;

naturalClickPosY = (naturalHeight / currentHeight) * currentClickPosY;

Have a look at this JSFiddle

自动填充
  • HTML

    <img src="http://placehold.it/1200x1000" width="1000">
    

    的JavaScript

    $('img').on("click", function(e){
        var $img = $(this);
        var currentClickPosX = e.pageX - $img.offset().left;
        var currentClickPosY = e.pageY - $img.offset().top;
    
        var currentWidth = $img.width();
        var currentHeight = $img.height();
    
        var naturalWidth = this.naturalWidth;
        var naturalHeight = this.naturalHeight;
    
        var naturalClickPosX = ((naturalWidth / currentWidth) * currentClickPosX).toFixed(0);
        var naturalClickPosY = ((naturalHeight / currentHeight) * currentClickPosY).toFixed(0);
    
        alert("Current X: " + currentClickPosX + " Current Y: " + currentClickPosY + 
              "\r\nNatural X: " + naturalClickPosX + " Natural Y: " + naturalClickPosY);
    });
    
  • 答案 1 :(得分:0)

    试试这个,将适用于所有尺寸

               $('.img-coordinate').click(function(e){
                var parentOffset = $(e.target).parent().offset();
                // here the X and Y on Click
                X = e.pageX - $(e.target).offset().left;
                Y = e.pageY - $(e.target).offset().top;
                    alert(X + ' , ' + Y );
                });
    

    工作fiddel:https://jsfiddle.net/h09kfsoo/