gpt4 book ai didi

javascript - 如何在不增加尺寸的情况下放大图像?

转载 作者:数据小太阳 更新时间:2023-10-29 05:09:07 28 4
gpt4 key购买 nike

我想在图像上获得缩放效果但不增加其在屏幕上的大小,我能够使用“transform:scale()”使图像获得某种缩放效果,但我不希望它占用的空间增加了,这就是我增加比例 () 时发生的情况。

我怎样才能得到这个?目前我实现的效果是在我的测试站点,以后会是博客/作品集:http://marcosroot.pythonanywhere.com/blog/

将鼠标悬停在图像中会产生这种效果。

PS:代码如下所示:

&__media {
transition: transform .25s ease-in-out;

&:hover {
transform: scale(1.025);
}
}

最佳答案

这种方法没有依赖性,适用于所有现代浏览器。 JavaScript 通过 setProperty 更新 CSS 变量,当您移动鼠标时,缩放图像的 background-position 会动态更新.

enter image description here

const zoomify = (width, height) => {
const el = document.querySelector('.zoomify');
el.style.width = `${width}px`;
el.style.height = `${height}px`;
el.addEventListener('mousemove', handleMouseMove, false);
}

function handleMouseMove(e) {
const dimensions = this.getBoundingClientRect();
const [x, y] = [
e.clientX - dimensions.left,
e.clientY - dimensions.top
];
const [percentX, percentY] = [
Math.round(100 / (dimensions.width / x)),
Math.round(100 / (dimensions.height / y))
];
this.style.setProperty('--mouse-x', percentX);
this.style.setProperty('--mouse-y', percentY);
}

zoomify(320, 212);
* {
box-sizing: border-box;
}

html,
body {
padding: 10px;
}

.starting-image {
width: 100%;
height: 100%;
}

.zoomify {
display: inline-block;
position: relative;
overflow: hidden;
}

.zoomify::after {
content: '';
position: absolute;
z-index: 1;
width: 100%;
height: 100%;
opacity: 0;
background-image: url("https://images.unsplash.com/photo-1528763216729-fb67cba479db?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=728e3916b52b079634aa7c7f82af612d&auto=format&fit=crop&w=6774&q=80%206774w,%20https://images.unsplash.com/photo-1528763216729-fb67cba479db?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=728e3916b52b079634aa7c7f82af612d&auto=format&fit=crop&w=6774&q=80%206774w");
background-size: cover;
background-position: center center;
background-repeat: no-repeat;
will-change: background-position;
}

.zoomify:hover .starting-image {
opacity: 0;
position: absolute;
}

.zoomify:hover::after {
opacity: 1;
background-size: 250%;
cursor: zoom-in;
background-position: calc(var(--mouse-x) * 1%) calc(var(--mouse-y) * 1%);
}
<div class="zoomify">
<img class="starting-image" src="https://images.unsplash.com/photo-1528763216729-fb67cba479db?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=728e3916b52b079634aa7c7f82af612d&auto=format&fit=crop&w=6774&q=80%206774w,%20https://images.unsplash.com/photo-1528763216729-fb67cba479db?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=728e3916b52b079634aa7c7f82af612d&auto=format&fit=crop&w=6774&q=80%206774w" alt="diner">
</div>

关于javascript - 如何在不增加尺寸的情况下放大图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54660838/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com