微信小程序旋转图片(canvas)获得文件的临时路径 (本地路径)

需求:微信小程序将拍照得到的图片,逆时针旋转180度,获得旋转的图片路径
思路:拍照得到的图片用canvas显示,旋转canvas,将旋转后的canvas转图片

<!-- 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//这个就是要的路径了
				}
			})
		}
	})
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值