<!--pages/API/Camera/index.wxml--> <view class="box"> <view class='title'>照相和攝像</view> <view> <button type='primary' bindtap="chooseimage">獲取圖片</button> <image mode="scaleToFill" src="{{imgPath}}"></image> <button type='primary' bindtap="chooseVideo">獲取視頻</button> <video class="video" src="{{videoPath}}"></video> </view> </view>
<image mode="scaleToFill" src="{{imgPath}}"></image>縮放圖片,全部填充圖片組件的范圍
/* pages/API/Camera/index.wxss */ page { background-color: #f8f8f8; height: 100%; } button { margin: 20rpx; } image { background-color: gainsboro; height: 200px; width: 100%; } video { width: 100%; height: 200px; }
// pages/API/Camera/index.js Page({ chooseimage: function() { var that = this; wx.chooseImage({ count: 1, // 默認9,設置選取照片的個數 sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有 sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,默認二者都有 success: function(res) { // 返回選定照片的本地文件路徑列表,tempFilePath可以作為img標簽的src屬性顯示圖片 that.setData({ imgPath: res.tempFilePaths }) } }) }, chooseVideo: function() { var that = this; wx.chooseVideo({ sourceType: ['album', 'camera'], maxDuration: 60,//視頻最大時長 camera: ['front', 'back'],//前攝像頭還是后攝像頭拍攝 success: function(res) {//接口調用成功首先顯示一個消息提示框 wx.showToast({ title: res.tempFilePath,//標題是選擇視頻的路徑 icon: 'success', duration: 2000 }) that.setData({ videoPath: res.tempFilePath//視頻路徑渲染到wxml文件,從而顯示這個視頻 }) } }) } })
this賦值給that,涉及到了success: function(res) 回調函數,當在回調函數中使用this的時候容易引起當前對象的變化,因此賦值給臨時變量
chooseImage函數,只有一個對象類型的參數

API函數wx.chooseImage()的使用方法
wx.chooseImage(Object object)從本地相冊選擇圖片或使用相機拍照 。 其參數屬性如下:
success 回調函數的參數屬性
tempFiles 對象數組元素屬性
API函數wx.chooseVideo()的使用方法
wx.chooseVideo(Object object)用於拍攝視頻或從手機相冊中選擇視頻。 其參數屬性如下:
success 回調函數的參數屬性