我正在做一个元素,我有一个包含如下图片的幻灯片:
img {
width:100vw;
height:100vh;
object-fit:cover;
}
这使得图像全屏并且表现得像 background-size:cover,因此它们在任何屏幕尺寸上都可以填满整个视口(viewport)而不会失真。
我想在这些图像上用文本工具提示标记某些点。为此,我找到了 Tim Severien's Taggd ,这在响应式图像上效果很好,但在我的例子中,object-fit:cover;
属性使标记的位置不准确。
我已经尝试了从 CSS hack 到改进 Tim 代码的所有方法,但我没有想法。如果您有任何解决方案或解决方法,请分享。
谢谢!
最佳答案
其实我也想做同样的事情。 这是我所做的。 也许它会在将来帮助某人。 如果这个功能可以集成到 taggd 中,那就太好了。
function buildTags()
{
// be aware that image.clientWidth and image.clientHeight are available when image is loaded
var croppedWidth = false;
var expectedWidth = 0;
var croppedWidthHalf = 0;
var imageWidth = 0;
var croppedHeight = false;
var expectedHeight = 0;
var croppedHeightHalf = 0;
var imageHeight = 0;
var naturalRatio = image.naturalWidth/image.naturalHeight;
var coverRatio = image.clientWidth/image.clientHeight;
if(Math.abs(naturalRatio - coverRatio) < 0.01)
{
// the image is not cropped, nothing to do
}
else
{
if(naturalRatio > coverRatio)
{
// width is cropped
croppedWidth = true;
expectedWidth = image.clientHeight * naturalRatio;
croppedWidthHalf = (expectedWidth - image.clientWidth)/2;
imageWidth = image.clientWidth;
}
else
{
// height is cropped
croppedHeight = true;
expectedHeight = image.clientWidth / naturalRatio;
croppedHeightHalf = (expectedHeight - image.clientHeight)/2;
imageHeight = image.clientHeight;
}
}
function calcy(y)
{
if(croppedHeight)
{
var positiony = y * expectedHeight;
if(positiony > croppedHeightHalf)
return (positiony - croppedHeightHalf)/imageHeight;
else // tag is outside the picture because cropped
return 0; // TODO : handle that case nicely
}
else
return y;
}
function calcx(x)
{
if(croppedWidth)
{
var positionx = x * expectedWidth;
if(positionx > croppedWidthHalf)
return (positionx - croppedWidthHalf)/imageWidth;
else // tag is outside the picture because cropped
return 0; // TODO : handle that case nicely
}
else
return x;
}
var tags = [
Taggd.Tag.createFromObject({
position: { x: calcx(0.74), y: calcy(0.56) },
text: 'some tag',
}),
Taggd.Tag.createFromObject({
position: { x: calcx(0.9), y: calcy(0.29) },
text: 'some other tag',
}),
....
];
var taggd = new Taggd(image, options, tags);
}
$(window).bind("load", function() {buildTags();});
关于javascript - 响应式、适合封面的图像标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45125926/