微信小程序实现手持弹幕功能开发

748 阅读1分钟

一、是不是你想要的效果,可扫小程序码查看一把先:

手持弹幕小程序吗.png

二、实现步骤:

1. wxml写一个text,弹幕文字

<view class="container" bind:tap="toggleBar">
  <text class='scorll-text' animation="{{scorll}}" style='color:{{color}};font-size:{{fontSize}}rpx;'>{{displayText}}</text>
</view>

2. wxss样式让文字横屏展示

.container {
  width: 100vh;
  height: 100vw;
  background-color: #000;
  overflow: hidden;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(90deg);
  line-height: 1;
}

.scorll-text {
  padding-left: 100vh;
  position: absolute;
  top: 50%;
  left: 0;
  white-space: nowrap;
  margin-top: -.5em;
}

3. js中创建动画:

   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    var animation = wx.createAnimation({
      timingFunction: 'linear'
    })
    this.data._animation = animation;
    this.scorllFuc();
  },

4. 执行动画:

   * 动画控制
   */
  scorllFuc: function () {
    this.getTextLen();
    // 获取文字长度是个异步的,需要等一会儿才行:
    setTimeout(() => {
      // 延迟是因为获取text的长度是异步的,需要等一小会儿:
      var scorllH = this.data._textLen;
      console.log(this.data._textLen)
      this.data.scorllDuration = parseInt(scorllH / this.data._currentSpeed);
      var scorllAmt = () => {
        this.data._animation.translate3d(-scorllH, 0, 0).step({
          duration: this.data.scorllDuration
        })
        this.data._animation.translate3d(0, 0, 0).step({
          duration: 0
        })
        this.setData({
          scorll: this.data._animation.export()
        })
      };
      scorllAmt();
      // 循环动画
      timer = setInterval(() => {
        scorllAmt();
      }, this.data.scorllDuration + 500);
    }, 300);
  },

  /**
   * 查询字幕长度
   */
  getTextLen: function () {
    var query = wx.createSelectorQuery();
    query.select('.scorll-text').boundingClientRect((obj) => {
      this.setData({
        _textLen: parseInt(obj.height)
      })
      console.log('query.select', obj.height)
    }).exec();
  },

三.感觉有用的话,可以打赏一把么?一毛不嫌少,100不嫌多

21673408689_.pic.jpg