我让(矩形)图像无限旋转。旋转时,我想调整其大小(以免图像被截断)。
换句话说:我尝试总是尽可能大地显示整个图像。
因此,“0 度”示例是正确的,但“80 度”示例更像是:
您可能已经注意到,这是作为 StreamElements-widget 执行的。这可能是不起作用的原因overflow:visible
。
HTML:
<div class="main-container">
<img src="some_url">
</div>
CSS:
.main-container {
width:100%;
height:100%;
overflow:visible;
display: grid;
place-items: center;
}
img {
max-width: 100%;
object-fit: contain;
animation: spin 5s infinite linear;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
I thought that transform: ... scale(x)
may work, but I wasn't able to do it without using fixed keyframe values (which seems like a unreliable solution).
I think you can't get your way through this without Javascript and also transform the element in Javascript instead of CSS. Here is how I would do it, I didn't reproduce your exact example, I used 2 simple divs : one container and another one inside the first one (instead of the image) ;
const cont= document.querySelector('.main-container');
const rot= document.querySelector('.rotater');
const H= rot.offsetHeight, h= cont.offsetHeight;
const W= rot.offsetWidth;
var t=0;
var anim= setInterval(rotate, 20);
function rotate(){
rot.style.transform= "rotate(-" + t + "deg)";
update(t);
t++;
}
function update(T){
let alpha= Math.atan(H/W);
let diagLength= Math.sqrt(
Math.pow(H, 2) + Math.pow(W, 2));
let theta= degToRad(T);
theta= radTrunc(theta);
theta= (theta> Math.PI/2 && theta< Math.PI) || (theta> 3*Math.PI/2 && theta< 2*Math.PI) ? Math.PI - theta : theta;
let beta= (Math.PI/2) - (alpha + theta);
let nonScaledHeight= Math.cos(beta) * diagLength;
let ratio= Math.abs(h/nonScaledHeight);
ratio= ratio> 1 ? 1 : ratio;
rot.style.transform += " scale(" + ratio + ")";
}
function degToRad(angle){
return angle * Math.PI / 180;
}
function radTrunc(angle){
while(angle> (Math.PI * 2)){
angle -= Math.PI*2;
}
return angle;
}
.main-container{
width: 600px;
height: 200px;
background: blue;
}
.rotater{
width: 250px;
height: 200px;
background: green;
margin: auto;
}
<div class="main-container">
<div class="rotater"></div>
</div>
您在函数中看到的所有计算update
都是基本的三角学,我们计算内部 div 旋转时的高度:nonScaledHeight
该值与外部 div 高度的比率将是内部 div 的缩放比例。degToRad
将角度t
从度数转换为弧度并radTrunc
确保角度保持在范围内[0, 2*PI[
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句