目录

微信小程序系列二小程序常用功能跳转地图扫一扫人脸识别拍照拨打电话调整屏幕亮度文字可复制监听截屏...

【微信小程序系列:二】小程序常用功能:跳转地图、扫一扫、人脸识别、拍照、拨打电话、调整屏幕亮度、文字可复制、监听截屏…

一.先言:

(~ ̄▽ ̄)~,hello,微信小程序系列第二篇,介绍下小程序里的 前端常用功能api ,可以快速copy使用~

二.文字可复制:

小程序页面里的文字默认是没有长按复制功能的,需要套个标签来实现:

 <text user-select="{{true}}">哈哈</text>

点击按钮,直接复制文本,直接调用微信方法:

  wx.setClipboardData({
        data: '要复制文本,可用变量表示' ,
         success: function (res) {
               wx.showToast({
                 title: '复制成功',
                icon:"none",
                mask:"true"//是否设置点击蒙版,防止点击穿透
              })
        }
     })

三.跳转地图:

有时显示一些地址需要在地图显示,这时可以直接借助跳转到小程序内置腾讯地图的api,直接自定义一个点击方法,然后在里面调用下面这个就行:

    wx.openLocation({
        longitude:  '',//纬度     必填
        latitude:  '',//经度     必填
        address: '',//地址的详细说明
        name:''//位置名
      }) 

效果如:

https://i-blog.csdnimg.cn/blog_migrate/5d637377122c67887d080317391ee719.png#pic_center

四.扫一扫:

有时候会调用扫码功能,就是相当于微信的扫一扫,扫码获取码值后进行相应操作。

    wx.scanCode({
      onlyFromCamera: true,// 是否只能从相机扫码,不允许从相册选择图片
      success(res){
         console.log("扫码成功:"+  JSON.stringify(res))
         //码值
         let codeResult = res.result
      },
      fail (err) {
       // Toast('无法识别该二维码')
        console.log(err)
      }
    })

五.拨打电话:

实现点击小程序某个按钮时,直接跳到手机拨打电话界面,且号码自动输入好,直接调下面方法就好。

  wx.makePhoneCall({   
      phoneNumber: '',      //需要拨打的电话号码
      success: function () {         
        console.log("拨打电话成功!")      
      },      
      fail: function () {        
        console.log("拨打电话失败!")      
      }    
    })  

六.调整屏幕亮度:

有时跳到小程序某个页面时,比如有二维码的页面,想要手机屏幕可以高亮度显示,怕用户看不清。注意的是,先把原先手机屏幕亮度在变量保存下来,当离开这个页面,要恢复原亮度,可在onUnload生命周期恢复。

    // 获取屏幕亮度
    wx.getScreenBrightness({
      success: function (res) {
        this.setData({
          ScreenBrightness: res.value //先把原先手机屏幕亮度在变量保存下来
        })
      }
    })
    
    //设置屏幕亮度
    wx.setScreenBrightness({
      value: 1,    //屏幕亮度值,范围 0~1,0 最暗,1 最亮
    })

七.监听截屏:

当用户用手机自带的截屏功能截屏的时候,可以监听到并显示个提示文字或其它操作啥的。

//监听截屏事件
wx.onUserCaptureScreen(function (res) {
  Toast('截屏成功,请不要将清远码交给他人')
})

八.人脸识别:

先得开通业务,然后代码直接调微信api方法即可,简单引用如下:

   let _this = this
    wx.startFacialRecognitionVerify({
      name: this.data.name, //身份证姓名
      idCardNumber:  this.data.idCard, //身份证号码
      success: function (res) {
        if (res.errCode === 0 || res.errMsg === "startFacialRecognitionVerify:ok") {
          var verifyResult = res.verifyResult; //认证结果
          console.log(verifyResult, '认证结果')
          // 认证成功
        }else{
          return
        }
      },
      checkAliveType: 2, //屏幕闪烁(人脸核验的交互方式,默认0,读数字)
      fail: err => {
        console.log(err, 'err')
      }
    })

九.拍照:

有两种方法,一种是调用调用wx.chooseImage方法,一种是camera标签自定义拍照页。

wx.chooseImage(Object object) ,调用后可以直接 相机拍照,也支持从相册选择

wx.chooseImage({
  count: 1,
  sizeType: ['original', 'compressed'],
  sourceType: ['album', 'camera'],
  success (res) {
    // tempFilePath可以作为 img 标签的 src 属性显示图片
    const tempFilePaths = res.tempFilePaths
     //小知识: 将图片转为base64
        const picBase64 = wx.getFileSystemManager().readFileSync(res.tempFilePaths[0], 'base64')
  }
})

camera标签就比较神奇,系统相机,可以自定义拍照页面,比如可以在相机拍摄页面加个蒙版框框啥的,可以 自定义拍摄页面样式

<camera device-position="back" flash="off" binderror="error" style="width: 100%; height: 300px;"></camera>
<button type="primary" bindtap="takePhoto">拍照</button>
<view>预览</view>
<image mode="widthFix" src="{{src}}"></image>
// camera.js
Page({
  takePhoto() {
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          src: res.tempImagePath
        })
      }
    })
  },
  error(e) {
    console.log(e.detail)
  }
})

后续补充:

1.提示小程序版本更新:

在app.js文件添加:

const updateManager = wx.getUpdateManager()

updateManager.onCheckForUpdate(function (res) {
  // 请求完新版本信息的回调
  console.log(res.hasUpdate)
})

updateManager.onUpdateReady(function () {
  wx.showModal({
    title: '更新提示',
    content: '新版本已经准备好,是否重启应用?',
    success: function (res) {
      if (res.confirm) {
        // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
        updateManager.applyUpdate()
      }
    }
  })
})

updateManager.onUpdateFailed(function () {
  // 新版本下载失败
})

2. 打开显示一个网页

要跳转的网页都得在它那服务器配置过才有权限跳。新建一个文件夹,包括wxml、wxss、json、js四个基本文件,专门用来打开网页链接的,改动其中wxml内容为:

<web-view src="{{path}}"></web-view>

path为网页的地址,这样就行了,就这么简单。

3. 显示富文本内容

微信小程序的富文本主要在rich-text标签显示:

  <rich-text  nodes="{{notice}}">
  </rich-text>

notice为文本内容。

小知识: 其中,有些富文本的图片比较大,可以用replace替换修改图片的样式,已达到在小程序正常显示的目的。

noticeContent = noticeContent.replace(/<img/gi,'<img style="max-width:100%;height:auto;margin:0 auto;display:block"')

4. 下载文件

  download(e) {
   //文件链接
    var url = e.currentTarget.dataset.url
    // 下载文件
    var downloadFile = ''
    // 把文件下载到一个临时文件中
    const downloadTask = wx.downloadFile({
      url: url,
      success: function (res) {
        // 下面是临时文件的路径
        const tempFilePath = res.tempFilePath;
        wx.saveFile({
          tempFilePath,
          success: function (res) {
            const savedFilePath = res.savedFilePath;
            // 打开文件
            wx.openDocument({
              filePath: savedFilePath,
              showMenu:true,
              success: function (res) {
              },
            });
          },
          fail: function (err) {
          }
        })
      },
      fail: function (err) {
      }
    })

    // 监控下载过程
    downloadTask.onProgressUpdate(function (res) {
    })
  },

上面的兼容不了ios,下面的可以:

   // 判断文件类型
   whatFileType(url){
    let sr = url.lastIndexOf('.') //  最后一次出现的位置
    let fileType = url.substr((sr+1)) // 截取url的类型
    return(fileType)
  },
  download(e){
    var url = e.currentTarget.dataset.url
    let fileTypes = ['doc','docx','xls','xlsx','ppt','pptx','pdf']
    let imageTypes = ["jpg", "jpeg", "png"]
    let fileType = this.whatFileType(url)
    let fileId = e.currentTarget.dataset.id
    wx.showLoading({
      title: '加载中',
    })
    wx.getSavedFileList({  // 获取文件列表
      success(res) {
        res.fileList.forEach((val, key) => { // 遍历文件列表里的数据
          // 删除存储的垃圾数据
          wx.removeSavedFile({
            filePath: val.filePath
          });
        })
      }
    })
    wx.downloadFile({
      url: url,
      filePath: wx.env.USER_DATA_PATH + "/"+ fileId + "."+fileType,
      method: 'GET',
      success: function(res){  
         if(fileTypes.includes(fileType)){
          wx.openDocument({
            filePath: res.filePath,
            showMenu: true,
            flieType: fileType,
            success: function (res) {
              wx.hideLoading()
              console.log('打开文档成功')
            },
            fail: function(err){
              wx.hideLoading()
              console.log('打开文档失败:', err)
            }
          });
         }else if(imageTypes.includes(fileType)){
          wx.hideLoading()
          wx.previewImage({
            showmenu: true,
            current: res.filePath, // 当前显示图片的http链接
            urls: [res.filePath] // 需要预览的图片http链接列表
          })
         }else{
          wx.hideLoading()
          wx.showModal({
            title: '提示',
            content: "文件类型不支持预览",
            showCancel: false
          })
         }
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: "下载超时",
          icon: 'none'
        })
        console.log('下载失败:', err);
      }
    })
  },

5.小程序overflow: scroll;不显示滚动条问题

::-webkit-scrollbar { width: 4px; height: 4px; color:#ffffff;}
::-webkit-scrollbar-track { -webkit-box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.3); box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1); border-radius: 10px; background-color:#FFFFFF;}
::-webkit-scrollbar-thumb { border-radius: 10px; -webkit-box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.3); box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1); background-color:rgb(170, 170, 170);}

6.扫描二维码微信小程序获取码内容:

后端设置码值时 scene:“t/123*a/456” , 不能"t=12;a=56" , 不然获取不到。因为=号不行,得特殊符号才行。

  analysisCode(options){
    // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
    var scene = decodeURIComponent(options.scene); 
    var obj = {};
    for (var i = 0; i < scene.split('*').length;i++){
      var arr = scene.split('*')[i].split('/');
      obj[arr[0]] = arr[1];
    }
    return obj
  },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

      let scene = null
      if(options.scene){
        // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
          scene = this.analysisCode(options.scene)
          console.log("二维码值scene is ", scene);
       }
 }

7.网络图片缓存到本地:

    ///把在线logo图片放本地服务器  重新启动小程序,去缓存中获取图片的缓存地址。 然后给Imagesrc赋值
      const path = wx.getStorageSync('image_logo')
      if (path) {
          console.log('path====', path)
          console.log('图片已缓存') // res.savedFilePath 为一个本地缓存文件路径  
        }else {
        wx.downloadFile({
          url: 'https://sbk.hrss.gdqy.gov.cn/ykttest/Integration/xcx/images/BrightQRCode/qy-logo.png',
          success: function(res) {
            if (res.statusCode === 200) {
              console.log('图片下载成功' + res.tempFilePath)
              // 第二步: 使用小程序的文件系统,通过小程序的api获取到全局唯一的文件管理器
              const fs = wx.getFileSystemManager()
              //  fs为全局唯一的文件管理器。那么文件管理器的作用是什么,我们可以用来做什么呢?
             //   文件管理器的作用之一就是可以根据临时文件路径,通过saveFile把文件保存到本地缓存.
              fs.saveFile({
                tempFilePath: res.tempFilePath, // 传入一个临时文件路径
                success(res) {
                  console.log('图片缓存成功', res.savedFilePath) // res.savedFilePath 为一个本地缓存文件路径  
                  wx.setStorageSync('image_logo', res.savedFilePath)
                }
              })
            }else {
              console.log('响应失败', res.statusCode)
            }
          }})
      }

十.总结:

暂时先这么多,写多了后面系列就没得写了,哈哈。欲知后事如何,请看下集~

不得不说,10月出了好多番,都是高质量的,有没有追《灵能百分百》、《电锯人》等等等的

https://i-blog.csdnimg.cn/blog_migrate/2ec716fb21fe6f8dca7338433ab2dc2e.png

Gitee仓库地址:

其它文章:

~关注我看更多简单创意特效:

…等等