javascript - 如何使用`object-fit:contain`获取图像像素坐标
问题描述
我目前正在显示具有object-fit: contain
属性的图像,以确保保留纵横比并显示完整图像。
但是,现在,我需要对单击此图像做出反应,并获取单击点相对于图像原点的坐标。
有没有办法做到这一点?还是我应该自己重新计算实际位置偏移?
解决方案
@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
推荐阅读
- json - 我无法使用 API POST 函数解决错误
- python-3.x - 杀死openhab打开的进程不起作用
- data-structures - 是否存在具有多个根节点的树结构,如果有,它叫什么?
- android - 无法在带有事件的 Gdevelop 事件中执行操作
- php - 为什么 is_numeric() 在传递看似数字的字符串时返回 false?
- go - Go 测试在带有 gopls 的 Emacs lsp-mode 中失败,但在 shell 中成功
- list - 如何支持 MutableList
具有 MutableList 的字段 - c - ASCII 值大于 127
- javascript - 如何在自定义文本输入中使用 onChange 反应原生
- facebook - Facebook Graph API /{group}/feed 仅列出我发布的帖子