由于自己在開發(fā)的過程中,需要用到拍照后立即按指定區(qū)域切圖,于是就研究了一下小程序的拍照功能,以下是效果圖,具體代碼看我的GitHub,有不懂的地方可以留言交流。
IMG_0978.PNG
IMG_0979.PNG

IMG_0C286DAD5062-1.jpeg
在代碼中主要用到了cover,在相機(jī)上面進(jìn)行繪制,詳細(xì)了解請看我的GitHub
關(guān)鍵代碼
<view style='width:{{width}}px; height:{{height}}px; overflow:hidden;'>
<camera device - position="back" flash = "off" style="width:{{width}}px; height:{{height}}px; margin-left:0px">
<cover-image src='{{logo}}' class= 'takephoto' bindtap='takePhoto' style='width:150px; height:150px; position:absolute; bottom:30px; left:{{(width-150)/2}}px;'> </cover-image>
<!--上部線條 -->
<cover-view class= 'biaochi' style = 'top:{{gap}}px; left:{{gap}}px; width:{{width-gap*2}}px; height:2px;'> </cover-view>
<!--下部線條 -->
<cover-view class= 'biaochi' style = 'top:{{gap+50}}px; left:{{gap}}px; width:{{width-gap*2}}px; height:2px;'> </cover-view>
<!--右部線條 -->
<cover-view class= 'biaochi' style = 'top:{{gap}}px; right:{{gap}}px; width:2px; height:50px;'> </cover-view>
<!--左部線條 -->
<cover-view class= 'biaochi' style = 'top:{{gap}}px; left:{{gap}}px; width:2px; height:50px;'> </cover-view>
</camera>
</view>
onLoad: function (options) {
var that = this
that.path = options.path
wx.getSystemInfo({
success: function (res) {
var width = res.windowWidth
var height = res.windowHeight
var gap = 20
that.setData({
width:width,
height:height,
gap: gap
})
wx.getImageInfo({
src: that.path,
success: function(res){
that.canvas = wx.createCanvasContext("image-canvas", that)
//過渡頁面中,圖片的路徑坐標(biāo)和大小
that.canvas.drawImage(that.path, 0, 0, that.data.width, that.data.height)
wx.showLoading({
title: '數(shù)據(jù)處理中',
mask: true
})
that.canvas.setStrokeStyle('red')
// 這里有一些很神奇的操作,總結(jié)就是MD拍出來的照片規(guī)格居然不是統(tǒng)一的
//過渡頁面中,對裁剪框的設(shè)定
that.canvas.strokeRect(that.data.gap, that.data.gap, that.data.width - 2 * that.data.gap, 50)
that.canvas.draw()
setTimeout(function () {
wx.canvasToTempFilePath({//裁剪對參數(shù)
canvasId: "image-canvas",
x: that.data.gap,//畫布x軸起點
y: that.data.gap,//畫布y軸起點
width: that.data.width - 2 * that.data.gap,//畫布寬度
height: 50,//畫布高度
destWidth: that.data.width - 2 * that.data.gap,//輸出圖片寬度
destHeight: 50,//輸出圖片高度
canvasId: 'image-canvas',
success: function (res) {
that.filePath = res.tempFilePath
//清除畫布上在該矩形區(qū)域內(nèi)的內(nèi)容。
that.canvas.clearRect(0, 0, that.data.width, that.data.height)
that.canvas.drawImage(that.filePath, that.data.gap, that.data.gap, that.data.width - that.data.gap*2, 50)
that.canvas.draw()
wx.hideLoading()
//在此可進(jìn)行網(wǎng)絡(luò)請求
},
fail:function(e){
wx.hideLoading()
wx.showToast({
title: '出錯啦...',
icon: 'loading'
})
}
});
}, 1000);
}
})
}
})
},
})