首页 > 解决方案 > 如何使用`object-fit:contain`获取图像像素坐标

问题描述

我目前正在显示具有object-fit: contain属性的图像,以确保保留纵横比并显示完整图像。

但是,现在,我需要对单击此图像做出反应,并获取单击点相对于图像原点的坐标。

有没有办法做到这一点?还是我应该自己重新计算实际位置偏移?

标签: javascripthtml

解决方案


@mousetail 似乎是对的,除了我自己的代码,我什么也没找到。它仅适用于object-fit: contain使用默认object-position值的情况。

    const image = document.querySelector('img')
    const matrix = new DOMMatrix()

    // First, center the image
    const elementCenter = new DOMPoint(image.clientWidth / 2, image.clientHeight / 2)
    const imageCenter = new DOMPoint(image.naturalWidth / 2, image.naturalHeight / 2)
    matrix.translateSelf(elementCenter.x - imageCenter.x, elementCenter.y - imageCenter.y)

    // And now zoom
    // Containing the object take the minimal zoom
    const zoom = Math.min(image.clientWidth / image.naturalWidth, image.clientHeight / image.naturalHeight)
    matrix.scaleSelf(zoom, zoom, 1, imageCenter.x, imageCenter.y)

    // Have fun

最后,如果你想转换一个点(例如从 a MouseEvent),那么你必须在它上面应用反向矩阵:

const point = new DOMPoint(12, 13)
const imagePoint = matrix.inverse().transformPoint(point)

请注意,此转换应在图像本身的 CSS 属性转换之后应用。transform


推荐阅读