微信小程序操作图片放大、缩小、旋转、拖拽
在开发小程序的时候遇到了上传图片,然后编辑的需求。打算网上找一下相关代码组件的,就不用自己搞这么麻烦。经过一番折腾,还是没有找到如意的,最后自己弄好了,记录一下。
思路
用一个变量装着图片的全部编辑数据,包括偏移的x 和y、放大缩小的倍数、图片旋转的角度。每当这个变量改变的时候都重新绘制一下图片。
imgdata: {
offsetX: 0, //剪裁图片左上角坐标x
offsetY: 0, //剪裁图片左上角坐标y
zoom: false, //是否缩放状态
distance: 0, //两指距离
scale: 1, //缩放倍数
rotate: 0 //旋转角度
},
上传图片
uploadTap() {
//首次上传本地图片
let _this = this
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success(res) {
_this.setData({
originUrl: res.tempFilePaths[0],//图片的本地路径
cropperResult: ''
})
_this.initImg(res.tempFilePaths[0]);
}
})
}
canvas
<canvas class='img' style="width: {{width2}}px; height: {{height2}}px;" canvas-id='canvas' catchtouchstart="touchstartCallback" catchtouchmove="touchmoveCallback" catchtouchend="touchendCallback">
</canvas>
画图
drawImg(){
let _this = this;
let bili = 1;
ctx.save();
let x = (_this.data.originImg.width - _this.data.originImg.width * cropData.scale) / 2;
let y = (_this.data.originImg.height - _this.data.originImg.height * cropData.scale) / 2;
//画布中点坐标转移到图片中心
let movex = (cropData.offsetX + x) * bili + _this.data.originImg.width * cropData.scale/2 ;
let movey = (cropData.offsetY + y) * bili + _this.data.originImg.height * cropData.scale/2;
ctx.translate(movex, movey); //translate 对坐标原点进行缩放
ctx.rotate(cropData.rotate * Math.PI / 180); //rotate 对坐标轴进行顺时针旋转
ctx.translate(-movex, -movey); //translate 对坐标原点进行缩放
let movex2 = (cropData.offsetX + x) ;
let movey2 = (cropData.offsetY + y) ;
ctx.translate(movex2, movey2); //translate 对坐标原点进行缩放
ctx.scale(cropData.scale, cropData.scale)
ctx.translate(-movex2, -movey2); //translate 对坐标原点进行缩放
ctx.drawImage(_this.data.originImg.url, (cropData.offsetX + x) * bili, (cropData.offsetY + y) * bili, _this.data.originImg.width * bili , _this.data.originImg.height * bili );//绘制图像
ctx.restore();
}
效果预览
先录入信息,然后就可以去到生成海报页面。完美ending