利用三角函数动态获取旋转角度

最近小程序要实现下图的样式效果,其中文字设置100%的行高并居中就行了,关键是父元素是响应式的,不同设备的宽高不同,线条需要旋转的角度也不相同,首先想到的就是利用三角函数求角度,不过在网上没有找到现成的方案,关于三角函数忘了差不多,又去复习了一下三角函数、w3c的Math中关于三角函数的api,花了两个多小时终于实现了。下面是代码。

<view class="goodsImgBg">
    <view style="transform:rotate({{360-rotate}}deg)"/>
    <view style="transform:rotate({{rotate}}deg)"/>
    <view style="transform:rotate({{180+rotate}}deg)"/>
    <view style="transform:rotate({{180-rotate}}deg)"/>
</view>

  

/**
   * 页面的初始数据
   */
  data: {
    rotate:68,
  },
  //根据设备宽高求旋转角度
  getAngle: function () {
    let height= wx.getSystemInfoSync().windowHeight;//获取设备高度
    let width=wx.getSystemInfoSync().windowWidth;//获取设备宽度度
    var rotate = Math.atan(width/height*92/24)/(Math.PI / 180);//根据三角函数获取需要旋转的弧度(92/24为view占设备的宽高比)
    rotate = Math.round(rotate);//根据弧度转换为角度
    console.log(rotate)
    this.setData({
      rotate
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getAngle();//获取旋转角度
  },
.goodsImgBg{
  200rpx;
  height: 200rpx;
  background: #ddd;
}
.goodsImgBg {
   92vw;
  height: 26vh; 
  background: rgba(0, 0, 0, 0.5);
  position: absolute;
  border-radius: 10rpx;
  text-align: center;
}
.goodsImgBg >view{
  position: absolute;
  1rpx;
  height: 40vw;
  background: #eee; 
}
.goodsImgBg >view:nth-child(1){
  margin:0;
  /* transform:rotate(-65deg); */
  transform-origin: right top;
}
.goodsImgBg >view:nth-child(2){
  margin-left:92vw;
  /* transform:rotate(65deg); */
  transform-origin: right top;
}
.goodsImgBg >view:nth-child(3){
  margin-top:26vh;
  /* transform:rotate(245deg); */
  transform-origin: right top;
}
.goodsImgBg >view:nth-child(4){
  margin-top:26vh;
  margin-left:92vw;
  /* transform:rotate(115deg); */
  transform-origin: right top;
}
原文地址:https://www.cnblogs.com/wang-sai-sai/p/13322943.html