Requisito: el applet de WeChat gira la imagen obtenida al tomar una foto 180 grados en sentido contrario a las agujas del reloj para obtener la ruta de la imagen girada.
Idea: la imagen obtenida al tomar una foto se muestra en un lienzo, gira el lienzo y convierte el lienzo girado en una imagen.
<!-- html -->
<canvas id="myCanvas" type="2d" :style="{width: canvasWidth+'rpx',height: canvasHeight+'rpx'}"></canvas>
//js
//微信小程序拍照
takePhoto() {
let that = this
const ctx = uni.createCameraContext()
ctx.takePhoto({
quality: "high",
success: res => {
//得到拍照的临时路径
that.imgUrl= res.tempImagePath
}
})
}
//获取拍摄图片的宽高作为canvas的宽高
getImageInfo() {
let that = this
wx.getImageInfo({
src: that.imgUrl,//得到拍照的临时路径
success: res => {
that.canvasHeight = that.canvasWidth * res.height / res.width
that.setCanvas()
},
fail: err => {
console.log(err, that.imgUrl)
}
})
}
//canvas显示拍照得到的图片
setCanvas() {
let that = this
//获取canvas
const query = wx.createSelectorQuery()
query.select('#myCanvas')
.fields({
node: true,
size: true
})
.exec(function(res) {
// console.log("res", res)
const canvas = res[0].node
canvas.width = that.canvasWidth
canvas.height = that.canvasHeight
const ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, that.canvasWidth, that.canvasHeight)
ctx.beginPath()
const bg = canvas.createImage()
bg.src = that.imgUrl
bg.onload = () => {
ctx.drawImage(bg, 0, 0, that.canvasWidth, that.canvasHeight)
}
})
}
//旋转图片
rotatePic() {
let that = this
//获取canvas
const query = wx.createSelectorQuery()
query.select('#myCanvas')
.fields({
node: true,
size: true
})
.exec(function(res) {
const canvas = res[0].node
canvas.width = that.canvasWidth
canvas.height = that.canvasHeight
const ctx = canvas.getContext('2d')
const bg = canvas.createImage()
bg.src = that.imgUrl
bg.onload = () => {
//先保存一下设置
ctx.save();
//将画布向右下移动一半宽
ctx.translate(canvas.width / 2, canvas.height / 2);
//再旋转角度:逆时针旋转180度
ctx.rotate(-180 / 180 * Math.PI);
//最后将画布移回来,摆正之前的位置
ctx.translate(-canvas.width / 2, -canvas.height / 2);
//最后画出来
ctx.drawImage(bg, 0, 0);
//不要忘记恢复之前的设置
ctx.restore()
//canvas转文件的临时路径 (本地路径)
wx.canvasToTempFilePath({
canvas,
fileType: "jpg",
quality: 1,
success: (res) => {
that.imgUrl = res.tempFilePath//这个就是要的路径了
}
})
}
})
}