1、页面路径 "pages/camera/takePhoto"
2、样式:takePhoto.wxss
.fullscreen{
width: 100%;
height: 100%;
}
.icon-take{
width: 150rpx;
height: 150rpx;
position: absolute;
z-index: 99;
bottom: 50rpx;
left: 300rpx;
}
.icon-change{
width: 65rpx;
height: 55rpx;
position: absolute;
z-index: 99;
bottom: 80rpx;
right: 80rpx;
}
.take-tip{
color: white;
position: absolute;
width: 250rpx;
z-index: 99;
bottom: 250rpx;
text-align: center;
left: 250rpx;
}
.cancel{
color: white;
position: absolute;
z-index: 99;
bottom: 80rpx;
left: 80rpx;
}
.sure{
color: white;
position: absolute;
z-index: 99;
bottom: 80rpx;
right: 80rpx;
}
2、布局:takePhoto.wxml
<block wx:if="{{showPreView}}">
<image class="fullscreen" src="{{imagePath}}"></image>
<cover-view class="cancel" bindtap="retake">重拍</cover-view>
<cover-view class="sure" bindtap="makeUse">使用照片</cover-view>
</block>
<block wx:else>
<camera device-position="{{isBackCamera?'back':'front'}}" flash="off" binderror="error" class="fullscreen" >
<cover-view class="cancel" bindtap="cancel">取消</cover-view>
<cover-view class="take-tip">轻触拍照</cover-view>
<cover-image class="icon-take" src="/images/icon_shoot.png" bindtap="takePhoto"></cover-image>
<cover-image class="icon-change" src="/images/icon_change.png" bindtap="changeCamera"></cover-image>
</camera>
</block>
3、javaScript:takePhoto.js
// pages/camera/takePhoto.js
const devicePositions = ['back','front']
var eventChannel
Page({
/**
* 页面的初始数据
*/
data: {
isBackCamera:true,
imagePath: '',//拍照路径
showPreView: false //显示图片预览
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
eventChannel = this.getOpenerEventChannel()
this.ctx = wx.createCameraContext()
},
error(e) {
console.log(e.detail)
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
wx.setKeepScreenOn({
keepScreenOn: true,
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
wx.setKeepScreenOn({
keepScreenOn: false,
})
},
takePhoto() {
if (this.data.showPreView) {
wx.showToast({
title: '已拍过,请重拍',
})
return
}
console.log('开始拍照。。。')
this.ctx.takePhoto({
quality: 'high',
success: (res) => {
this.setData({
imagePath: res.tempImagePath,
showPreView: true
})
wx.getImageInfo({
src: res.tempImagePath,
success:(res)=>{
console.log("图片信息",res)
}
})
console.log(res.tempImagePath)
}
})
},
retake() {
this.setData({
showPreView: false,
imagePath: null
})
},
changeCamera(){
let cameraPos = this.data.isBackCamera
this.setData({
isBackCamera:!cameraPos
})
},
/**
* 取消
*/
cancel(){
wx.navigateBack({
delta: 1,
})
},
//使用照片
makeUse(){
this.emitPhoto(this.data.imagePath)
wx.navigateBack({
delta: 1,
})
},
emitPhoto(path){
eventChannel.emit('photoCallback',{path:path})
}
})
4、配置:takePhoto.json
{
"usingComponents": {},
"navigationStyle":"custom"
}
5、使用
//拍照
takePicture() {
let _this = this
wx.navigateTo({
url: '/pages/camera/takePhoto',
events:{
photoCallback:function(data){
console.log(data)
//data.path 即为所拍照片的临时文件
}
}
})
}
- 初学小程序,请多多指教
- 用到的拍照按钮、切换摄像头按钮可自己添加相应图片