如何解决Sprite 框架作为 div 背景,在 div 旋转时自动缩放错误
正如标题所暗示的,我正在 div 背景上渲染一个精灵的框架。
一切正常,并正确调整大小,直到在 div 上应用旋转。 图像第一次加载到旋转后的div中时,比例是正确的,但是如果我们调整文档大小,框架比例就会变得不正确。
请参阅此 JSFIDDLE。要重现该问题,只需调整“结果”部分的大小。
代码:
HTML
<div class="img"></div>
CSS
body {
margin: 0;
padding: 0;
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.img {
overflow: hidden;
background-repeat: no-repeat;
background: url(https://image.freepik.com/free-vector/orange-mushroom-game-sprites_22191-71.jpg);
width: 50vw;
height: 50vw;
}
JS
const $img = document.querySelector('.img');
const firstFrameWidth = 185;
const firstFrameHeight = 155;
const firstFrameX = 0;
const firstFrameY = -10;
const spriteWidth = 626;
const spriteHeight = 348;
function resize() {
const bounds = $img.getBoundingClientRect();
const scaleX = bounds.width / firstFrameWidth;
const scaleY = bounds.height / firstFrameHeight;
const bgWidth = spriteWidth * scaleX;
const bgHeight = spriteHeight * scaleY;
const bgX = firstFrameX * scaleX;
const bgY = firstFrameY * scaleY;
$img.style.backgroundSize = `${bgWidth}px ${bgHeight}px`;
$img.style.backgroundPosition = `${firstFrameX}px ${firstFrameY}px`;
}
window.addEventListener('resize',resize);
resize();
$img.style.transform = 'rotate(45deg)';
有什么想法吗?
解决方法
我后来发现 getBoundingClientRect 从 window.getComputedStyles 返回不同的值...显然就像你说的,getBoundingClientRect 返回旋转后的高度和宽度,但我需要原始高度和宽度来缩放精灵所以技巧是使用 window.getComputedStyle。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。