demo
如题,具体的效果见这里 。做这样的效果的难点在于,计算没旋转前图片的宽,高和旋转后的宽高。
下面来看具体的实现。
/* 图片的父元素 */
.img-wrap{
display: flex;
justify-content: center;
align-items: center;
height: 400px;
}
function getImgSize (src) {
return new Promise(function (resolve, reject) {
$('<img/>', {
load: function () {
resolve({
width: this.width,
height: this.height
})
},
src: src
})
})
}
let $imgWrap = $('.img-wrap')
let wrapSize = {
width: $imgWrap.width(),
height: $imgWrap.height()
}
我们知道图片在旋转 (2n * 90)
度在父元素的宽高是一样的,((2n + 1) * 90)
度在父元素的宽高是一样的。所以我们只需要两组宽高。
图片的宽和高要满足
在上面的条件下,图片的宽高只有有限的值可以选。
(2n * 90)
度的情况下 ((2n + 1) * 90)
度的情况下 大概的代码如下
// this.imgSizeInfo 存旋转 (2n * 90) 度和旋转 ((2n + 1) * 90) 度的宽高
let imgRatio = imgSize.width / imgSize.height
let imgW = wrapSize.width
let imgH = imgW / imgRatio
if (imgH < wrapSize.height) {
this.imgSizeInfo.push([wrapSize.width + 'px', 'auto'])
} else {
this.imgSizeInfo.push(['auto', wrapSize.height + 'px'])
}
// 旋转((2n + 1) * 90) 度后
imgW = wrapSize.height
imgH = imgW / imgRatio
if (imgH < wrapSize.width) {
this.imgSizeInfo.push([wrapSize.height + 'px', 'auto'])
} else {
this.imgSizeInfo.push(['auto', wrapSize.width + 'px'])
}
旋转用 CSS3 的 transform: rotate(旋转角度)deg;
来实现。旋转后,需要从新设置图片宽高。
rotate: function (degree) {
this.rotateDegree += degree
this.styleObject.transform = `rotate(${this.rotateDegree}deg)`
if (this.rotateDegree % 180 === 0) {
this.styleObject.width = this.imgSizeInfo[0][0]
this.styleObject.height = this.imgSizeInfo[0][1]
} else {
this.styleObject.width = this.imgSizeInfo[1][0]
this.styleObject.height = this.imgSizeInfo[1][1]
}
}
对应的 html
<div class="target-wrap">
<div class="img-wrap">
<img src="demo.png" alt="" class="target" :style="styleObject">
</div>
<a href="javascript:void(0);" class="target-left-control" @click="rotate(-90)">左转90度</a>
<a href="javascript:void(0);" class="target-right-control" @click="rotate(90)">右转90度</a>
</div>
demo 的完整代码,见这里。
本文遵守创作共享CC BY-NC-SA 4.0协议 网络平台如需转载必须与本人联系确认。