小程序 web-view h5页面背景音乐自动播放

该代码展示了如何使用React和微信小程序开发年度账单页面,包括页面的滑动效果、音频播放控制以及数据渲染。通过AntDesign库进行UI组件构建,使用html2canvas将页面转换为图片,并提供了音效管理和页面导航功能。
摘要由CSDN通过智能技术生成

在这里插入图片描述

在这里插入图片描述

/**
 * 年度账单-登录首页
 */
import React,{useEffect} from 'react'
import 'swiper/swiper-bundle.min.css'
import styles from './styles.less'
import bgm from './bgm2.mp3'
// 主体
const annualAccountLoginIndex = (props) => {
  const goAnnualAccount =()=>{
    const {location: { query: { name,phone} } } = props;
    props.history.push({
      pathname: `/annualAccountLoginDetail`,
      query:{
        name,
        phone
      }
    })
  }
  const imgUrl = 'http://oss.yoyoeco.com/Image/annualbill2021/'
  useEffect(() => {
  	//  提前加载audio音乐
    const myAudio = new Audio()
    myAudio.preload = true;
    myAudio.autoplay = false;
    myAudio.loop = true;
    myAudio.src = bgm;
    document.getElementById("audioBox").appendChild(myAudio);
  }, [])
      
  return (
    <div className={styles.swpierBox} style={{background: `url(${imgUrl}index_bg.jpg) no-repeat center #000`,backgroundSize:'cover', height:'100vh'}}>
      <div id='audioBox' style={{ position: 'fixed', top: 15, right: 15, width: 40, height: 40, zIndex: 0 }} />
      <div className={styles.heart} style={{width:'41%',position:'fixed',top:'calc(52% + 5px)',left:'29.5%'}} onClick={goAnnualAccount}>
        <img style={{display:'block',width:'100%'}} src={`${imgUrl}index_button.png`} alt="" />
      </div>
    </div>
  )
}
export default annualAccountLoginIndex;

/**
 * 年度账单-详情页
 */
import React, { createRef, PureComponent, } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { connect } from 'dva';
import Swiper from 'swiper'
import moment from 'moment';
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/line';
import 'echarts/lib/chart/pie';
import 'echarts/lib/chart/bar';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import { message } from 'antd';
import styles from './styles.less';
import html2canvas from './html2canvas1.0.0-rc.4'; // 1.0.0-rc.4版本
import 'swiper/swiper-bundle.min.css'
import bgm from './bgm2.mp3'

// 主体内容
@connect(({ annualAccount, loading }) => ({
  annualAccount,
  loading: loading.models.annualAccount,
}))

@Form.create()
class annualAccountLoginDetail extends PureComponent {
  constructor(props) {
    super(props);
    this.gw = createRef();
    this.gw1 = createRef();
    this.state = {
      billData: {},
      imgUrl: `http://oss.yoyoeco.com/Image/annualbill2021/`,
      myAudio:{}
    }
  }

  // (装载完成),在render之后调用
  componentDidMount() {
    const { dispatch, location: { query: { phone} } } = this.props;
    dispatch({
      type: 'annualAccount/queryYearBills',
      payload: phone,
      callback: res => {
        const { data } = res
        this.setState(
          {
            billData: data,
          }
        );
      },
    });
    const mySwiper = new Swiper('.swiper-container', {
      direction: 'vertical',
      effect: 'fade',
      observer: true,
      observeParents: true,
      resistanceRatio: 0,
      autoHeight: true, // 高度随内容变化
      height: window.innerHeight,  // 高度占满整个设备高度
      paginationClickable: true,
      onTouchStart(swiper) {
        swiper.unlockSwipeToPrev();
        swiper.unlockSwipeToNext();
        if (swiper.isEnd) {
          swiper.lockSwipeToNext();
        } else if (swiper.activeIndex === 0) {
          swiper.lockSwipeToPrev();
        }
      }
    })
    // 音乐播放
    const myAudio = new Audio()
    myAudio.preload = true;
    myAudio.autoplay = true;
    myAudio.loop = true;
    myAudio.src = bgm;
    document.getElementById("audioBox").appendChild(myAudio);
    this.setState({
      myAudio
    })
    const play = function () {
      myAudio.play();
      document.removeEventListener("touchstart", play, false);
    };
    myAudio.play();
    document.addEventListener("WeixinJSBridgeReady", () => {// 微信
      play();
    }, false);
    document.addEventListener("touchstart", play, false);
  }

  playMusic=()=>{
    const {myAudio} = this.state
    myAudio.play()
  }

  muteMusic=()=>{
    const {myAudio} = this.state
    myAudio.pause()
  }

  // 返回首页
  goHome = () => {
    wx.miniProgram.navigateTo({ url: `/pages/start/start` })
  }

  // html转化成图片
  htmlToImg = () => {
    html2canvas(document.getElementById('picture1'), {
      dpi: 169 * 2,// window.devicePixelRatio * 2,
      scale: 2,
      logging: false, // 日志开关,便于查看html2canvas的内部执行流程
      scrollY: 0,
      scrollX: 0,
      useCORS: true,
      allowTaint: false
    })
      .then((canvas) => {
        const imageSrc = canvas.toDataURL("image/png", 1)
        this.doSavePic(imageSrc)
      }).catch(err => {
        message.info(err)
      });
  }

  changeData=(date2,type)=>{
    const reg = new RegExp( '-' , "g" )
    const date = date2.replace(reg,'/')
    const year = new Date(date).getFullYear()
    const month = new Date(date).getMonth() + 1
    const day = new Date(date).getDate()
    const hour = new Date(date).getHours() < 10 ? `0${new Date(date).getHours()}` : new Date(date).getHours()
    const min = new Date(date).getMinutes()< 10 ? `0${new Date(date).getMinutes()}` : new Date(date).getMinutes()
    let time 
    switch (type) {
      case 'MM月dd日':
        time = `${month}月${day}日`
        break;
      case 'X点XX分':
        time = `${hour}点${min}分`
        break;
      default:
        time = `${year}-${month}-${day}`
        break;
    }
    return time
  }

  getKeyWords=(num)=>{
    let txt = ''    
    if (num < 275001 ) {
      txt = '踩油门就像踩缝纫机'
    } else if (num > 275000 && num < 350001){
      txt = '消费力YYDS'
    } else if (num > 350000 && num < 625001) {
      txt = '佛系豚友'
    } else {
      txt = '加油,你差点就追上我了'
    }
    return txt
  }

  // 保存图片到相册
  doSavePic = (imgUrl) => {
    wx.miniProgram.postMessage({
      data: {
        imgData: imgUrl // 刚才拿到的base64 数据
      }
    });
    wx.miniProgram.navigateBack({ delta: 1 }) // 注意这里.
  }

  render() {
    const { billData,imgUrl } = this.state
    const {location: { query: { name} } } = this.props;
    return (
      <>
        <div className={styles.Hello}>
          <div id='audioBox' style={{ position: 'fixed', top: 15, right: 15, width: 40, height: 40, zIndex: 0 }} />
          <div style={{display:'flex',alignItems:'center',position: 'fixed',right:15,zIndex:999,top:15}}>
            <img src={`${imgUrl}4319d39a0edfbeb2c34655889cb488c.png`} onClick={this.muteMusic} alt="" style={{marginRight:10,width:30,height:30,display:'block',padding:5}} />
            <img onClick={this.playMusic} src={`${imgUrl}acb67f079a488b2a1c6cd2da00d4dd4.png`} alt="" style={{width:30,height:30,display:'block',padding:5.5}} />
          </div>
          <div className="swiper-container">
            <div className="swiper-wrapper">
              <div className="swiper-slide">
                <div className={styles.swpierBox} style={{ background: `url(${imgUrl}page2_bg.jpg) no-repeat center bottom #000`, backgroundSize: '100% auto', height: '100vh' }}>
                  <img src={`${imgUrl}page2_icon.png`} alt="" style={{ position: 'absolute', top: 25, left: 30, width: 100 }} />
                  <div className={styles.heart} style={{ position: 'absolute', bottom: '88px', left: '0', width: '100%' }}>
                    <div className={styles.textContent} style={{ fontSize: 18, fontWeight: 600, paddingBottom: 23 }}>嗨!{name},你好</div>
                    <div className={styles.textContent}>好久不见</div>
                    <div className={styles.textContent}>欢迎乘坐Y2021号宇宙飞船,我是本次航班的机长豚豚</div>
                    <div className={styles.textContent}>此次航班航行总里程520光年,预计用时1314秒</div>
                    <div className={styles.textContent}>本次旅行严禁携带忧伤、烦恼等危险品</div>
                    <div className={styles.textContent}>请带上愉快的心情,系好安全带</div>
                    <div className={styles.textContent}>跟随我一起开启元宇宙惊喜吧</div>
                  </div>
                </div>
              </div>
              <div className="swiper-slide">
                <div className={styles.swpierBox} style={{ background: `url(${imgUrl}page3_bg.jpg) no-repeat center bottom #000`, backgroundSize: '100% auto', height: '100vh' }} />
                <img src={`${imgUrl}page2_icon.png`} alt="" style={{ position: 'absolute', top: 25, left: 30, width: 100 }} />
                <div className={styles.heart} style={{ paddingLeft: 38, position: 'absolute', width: '100%', top: 200 }}>
                  <div className={styles.textContent2}>去征服世界,我为您加油</div>
                  <div className={styles.textContent2}>从2017,走到2021</div>
                  <div className={styles.textContent2}>。。目前已</div>
                  <div className={styles.textContent2}>布局 <span className={styles.spanText}>22个 </span> 省份 </div>
                  <div className={styles.textContent2}>点亮 <span className={styles.spanText}>71个 </span> 城市</div>
                </div>
              </div>
              <div className="swiper-slide">
                <div className={styles.swpierBox} style={{ background: `url(${imgUrl}page4_bg.jpg) no-repeat center bottom #000`, backgroundSize: '100% auto', height: '100vh' }} />
                <img src={`${imgUrl}page2_icon.png`} alt="" style={{ position: 'absolute', top: 25, left: 30, width: 100 }} />
                <img src={`${imgUrl}goOil.png`} onClick={this.goHome} alt="" style={{ position: 'absolute', top: 60, right: 20, width: 137 }} />
                <div className={styles.heart} style={{ paddingLeft: 38, position: 'absolute', width: '100%', bottom: 220 }}>
                  <div className={styles.textContent2}>在过去的一年里</div>
                  <div className={styles.textContent2}>YOYO—ECO智慧油站系统</div>
                  <div className={styles.textContent2}>为<span className={styles.spanText}>1575277位 </span>朋友</div>
                  <div className={styles.textContent2}>处理了<span className={styles.spanText}>15082339笔 </span>订单</div>
                  <div className={styles.textContent2}>平均每分钟完成了<span className={styles.spanText}>21次 </span>计算</div>
                  <div className={styles.textContent2}>距离成为12306那样的平台</div>
                  <div className={styles.textContent2}>还有2/3的路要走</div>
                </div>
              </div>
              <div className="swiper-slide">
                <div className={styles.swpierBox} style={{ background: `url(${imgUrl}page5_bg.jpg) no-repeat center bottom #000`, backgroundSize: '100% auto', height: '100vh' }} />
                <img src={`${imgUrl}page2_icon.png`} alt="" style={{ position: 'absolute', top: 25, left: 30, width: 100 }} />
                <img src={`${imgUrl}page5_popo.png`} alt="" style={{ position: 'absolute', top: 0, left: 0, width: '100%', zIndex: 0 }} />
                <div className={styles.heart} style={{ paddingLeft: 38, position: 'absolute', width: '100%', top: 160, zIndex: 2 }}>
                  <div className={styles.textContent2}>2021年,便利店</div>
                  <div className={styles.textContent2} style={{ position: 'relative' }}>共计卖出了<span className={styles.spanText}>18900个</span><img src={`${imgUrl}page5_pic.png`} alt="" style={{ position: 'absolute', bottom: 0, left: 210, width: 95, zIndex: 1 }} /></div>
                  <div className={styles.textContent2}>YOUNG-小红<span className={styles.spanText}>虎皮凤爪</span></div>
                  <div className={styles.textContent2}>有<span className={styles.spanText}>9450只</span>小鸡失去了</div>
                  <div className={styles.textContent2}>他们的小jio jio</div>
                </div>
              </div>
              {
                billData && billData.firstOilTime ?
                  <>
                    <div className="swiper-slide">
                      <div className={styles.swpierBox} style={{ background: `url(${imgUrl}page6_bg.jpg) no-repeat center bottom #000`, backgroundSize: '100% auto', height: '100vh' }} />
                      <img src={`${imgUrl}page2_icon.png`} alt="" style={{ position: 'absolute', top: 25, left: 30, width: 100 }} />
                      <div className={styles.heart} style={{ paddingLeft: 60, position: 'absolute', width: '100%', bottom: 250 }}>
                        <div className={styles.textContent2}>还记得2021年<span className={styles.spanText}>{moment(billData.firstOilTime).format('MM月DD日')}</span>吗</div>
                        <div className={styles.textContent2}>你踏入<span className={styles.spanText}>{this.changeXHT(billData.firstOilGasName)}</span></div>
                        <div className={styles.textContent2}>加了第一箱油</div>
                        <div className={styles.textContent2}>消费了 <span className={styles.spanText}>{billData.firstOilAmount/100}元</span></div>
                        <div className={styles.textContent2}>宇宙中的原子用140亿年</div>
                        <div className={styles.textContent2}>穿越时间和空间来创造我们</div>
                        <div className={styles.textContent2}>为的是让我们彼此相遇</div>
                      </div>
                    </div>
                    {
                      billData && billData.oilOrderCount ?
                        <div className="swiper-slide">
                          <div className={styles.swpierBox} style={{ background: `url(${imgUrl}page5_bg.jpg) no-repeat center bottom #000`, backgroundSize: '100% auto', height: '100vh' }} />
                          <img src={`${imgUrl}page2_icon.png`} alt="" style={{ position: 'absolute', top: 25, left: 30, width: 100 }} />
                          <img src={`${imgUrl}page7_bg2.png`} alt="" style={{ position: 'absolute', top: 40, left: 0, width: '100%', zIndex: 0 }} />
                          <div className={styles.heart} style={{ paddingLeft: 60, position: 'absolute', width: '100%', top: 147 }}>
                            <div className={styles.textContent2}>2021年,你在 <span className={styles.spanText}>{billData.oilCitys}</span></div>
                            <div className={styles.textContent2}>打卡过。。。</div>
                            <div className={styles.textContent2}>这一年</div>
                            <div className={styles.textContent2}>我为你加油 <span className={styles.spanText}>{billData.oilOrderCount}次</span></div>
                            <div className={styles.textContent2}>每一次跨越时空的相遇 </div>
                            <div className={styles.textContent2}>总会令人神往</div>
                          </div>
                        </div>
                      :
                      null
                    }
                    {billData && billData.nightOilTime?// 深夜加油
                      <div className="swiper-slide">
                        <div className={styles.swpierBox} style={{ background: `url(${imgUrl}page5_bg.jpg) no-repeat center bottom #000`, backgroundSize: '100% auto', height: '100vh' }} />
                        <img src={`${imgUrl}page2_icon.png`} alt="" style={{ position: 'absolute', top: 25, left: 30, width: 100 }} />
                        <img src={`${imgUrl}page8_bg2.png`} alt="" style={{ position: 'absolute', top: 55, left: 0, width: '100%', zIndex: 0 }} />
                        <div className={styles.heart} style={{ paddingLeft: 60, position: 'absolute', width: '100%', top: 207 }}>
                          <div className={styles.textContent2}>最晚一次加油~</div>
                          <div className={styles.textContent2}>{moment(billData.nightOilTime).format('MM月DD日')}<span className={styles.spanText}>{moment(billData.nightOilTime).format('HH点mm分')}</span></div>
                          <div className={styles.textContent2}>深夜里,你开车驶入。。。</div>
                          <div className={styles.textContent2}>星月为伴,我想对你说</div>
                          <div className={styles.textContent2}>你努力的样子So beautiful</div>
                        </div>
                      </div>
                    :null}
                    {billData && billData.maxOilQuantity ?// 加油最多 
                      <div className="swiper-slide">
                        <div className={styles.swpierBox} style={{ background: `url(${imgUrl}page9_bg.png) no-repeat center bottom #000`, backgroundSize: '100% auto', height: '100vh' }} />
                        <img src={`${imgUrl}page2_icon.png`} alt="" style={{ position: 'absolute', top: 25, left: 30, width: 100 }} />
                        <img src={`${imgUrl}page9_popo.png`} alt="" style={{ position: 'absolute', top: 160, left: 0, width: '100%', zIndex: 0 }} />
                        <div className={styles.heart} style={{ paddingLeft: 60, position: 'absolute', width: '100%', top: 55 }}>
                          <img src={`${imgUrl}page9_pic.png`} alt="" style={{ width: '85%', marginLeft: '-23px', marginBottom: 20 }} />
                          <div className={styles.textContent2}>{moment(billData.maxOilDatetime).format('MM月DD日')},也许是很特别的一天</div>
                          <div className={styles.textContent2}>你加了<span className={styles.spanText}> {billData.maxOilQuantity / 1000} 升</span> 油</div>
                          <div className={styles.textContent2}>是你2021年加油升数最多的一次</div>
                          <div className={styles.textContent2}>很高兴,这一次我能陪你的时间更久</div>
                          <div className={styles.textContent2}>走的更远</div>
                        </div>
                      </div>
                    : null}
                    {billData && billData.discountAmount ?// 优惠信息 
                      <div className="swiper-slide">
                        <div className={styles.swpierBox} style={{ background: `url(${imgUrl}page5_bg.jpg) no-repeat center bottom #000`, backgroundSize: '100% auto', height: '100vh' }} />
                        <img src={`${imgUrl}page2_icon.png`} alt="" style={{ position: 'absolute', top: 25, left: 30, width: 100 }} />
                        <img src={`${imgUrl}page10_popo.png`} alt="" style={{ position: 'absolute', top: '17%', left: 0, width: '87%', zIndex: 0 }} />
                        <div className={styles.heart} style={{ paddingLeft: 60, position: 'absolute', width: '100%', top: '28%' }}>
                          <div className={styles.textContent2}>这一年,你在。。。</div>
                          <div className={styles.textContent2}>使用了 <span className={styles.spanText}>{billData.couponCount}张</span> 优惠券</div>
                          <div className={styles.textContent2}>共省下了 <span className={styles.spanText}>{billData.discountAmount/100}元</span></div>
                          <div className={styles.textContent2}>剩余可用的积分 <span className={styles.spanText}>{billData.integralAll}个</span></div>
                          <div className={styles.textContent2}>省下来的,就是幸福的本钱</div>
                        </div>
                      </div>
                     : null}
                    {billData && billData.oilOrderQuantity ?// 会员消费汇总 
                      <div className="swiper-slide">
                        <div className={styles.swpierBox} style={{ background: `url(${imgUrl}page2_bg.jpg) no-repeat center bottom #000`, backgroundSize: '100% auto', height: '100vh' }}>
                          <img src={`${imgUrl}page2_icon.png`} alt="" style={{ position: 'absolute', top: 25, left: 30, width: 100 }} />
                          <div className={styles.heart} style={{ position: 'absolute', bottom: '88px', left: '0', width: '100%' }}>
                            <div className={styles.textContent} style={{ fontSize: 18, fontWeight: 600, paddingBottom: 23 }}>尊敬的各位旅客</div>
                            <div className={styles.textContent}>。。。Y2021号宇宙飞船即将到站</div>
                            <div className={styles.textContent}>2021这一站,你在。。。累计加注{billData.oilOrderQuantity/1000}升汽油</div>
                            <div className={styles.textContent}>在。。。大家族中消费排名第{billData.quantityNumber}位</div>
                            <div className={styles.textContent}>你的年度消费关键词:<span className={styles.spanText}>{this.getKeyWords(billData.quantityNumber)}</span></div>
                            <div className={styles.textContent}>这一年,日迈月征,朝暮轮转</div>
                            <div className={styles.textContent}>。。。何其有幸,与你共度</div>
                            <div className={styles.textContent}>请携带好你的回忆,我们一起奔向2022</div>
                          </div>
                        </div>
                      </div>
                     : null} 
                  </>
                  :
                  <div className="swiper-slide"> {/* 未登录的话走到这 */}
                    <div className={styles.swpierBox} style={{ background: `url(${imgUrl}page6_bg.jpg) no-repeat center bottom #000`, backgroundSize: '100% auto', height: '100vh' }} />
                    <img src={`${imgUrl}page2_icon.png`} alt="" style={{ position: 'absolute', top: 25, left: 30, width: 100 }} />
                    <div className={styles.heart} style={{ paddingLeft: 103, position: 'absolute', width: '100%', bottom: 320 }}>
                      <div className={styles.textContent2} style={{ fontSize: 22, fontWeight: 600 }}>新的一年</div>
                      <div className={styles.textContent2} style={{ fontSize: 22, fontWeight: 600 }}>要加油哦</div>
                    </div>
                  </div>
              }
            </div>
          </div>
        </div>
      </>
    )
  }
}
export default annualAccountLoginDetail;
好的,针对你的问题,我可以给你一些思路和实现方式。 在微信小程序中,我们可以使用自定义组件来封装一些常用的UI组件或者业务逻辑组件,具体可以参考微信小程序官方文档中的自定义组件部分。而在H5页面中,我们可以使用微信小程序web-view组件嵌入小程序页面,从而实现小程序组件在H5页面中的调用。 接下来,我们需要在小程序中定义一个自定义组件,并将其封装为一个可以在web-view中调用的方法。具体实现步骤如下: 1. 在小程序中定义自定义组件,并实现相应的业务逻辑。 2. 在自定义组件中添加一个事件监听器,用来接收来自web-view的消息。 3. 在web-view中使用postMessage()方法发送消息给小程序,消息内容为需要调用的方法名及相应的参数。 4. 在自定义组件中根据接收到的消息内容,调用相应的方法并返回结果给web-view。 下面是一个简单的示例代码: 小程序端代码: ```javascript // 定义自定义组件 Component({ methods: { // 自定义方法 add: function(a, b) { return a + b; }, // 监听web-view发送的消息 onMessage: function(e) { // 解析消息内容 var data = JSON.parse(e.detail.data); // 调用相应的方法并返回结果 if (data.method == 'add') { var result = this.add(data.a, data.b); wx.webViewPostMessage({ data: JSON.stringify({ method: 'add', result: result }) }); } } } }) ``` H5页面端代码: ```javascript // 获取web-view组件 var webview = document.getElementById('webview'); // 发送消息给小程序 webview.contentWindow.postMessage(JSON.stringify({ method: 'add', a: 1, b: 2 }), '*'); // 监听小程序返回的消息 window.addEventListener('message', function(e) { // 解析消息内容 var data = JSON.parse(e.data); // 处理返回结果 if (data.method == 'add') { console.log('1 + 2 = ' + data.result); } }); ``` 通过以上代码实现,我们就可以在H5页面中调用小程序中封装的方法了。需要注意的是,为了保证安全性,我们在发送消息时需要指定目标源,所以在postMessage()方法中需要指定'*'或者目标web-view的src属性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值