最近在开发小程序,产品经理提了一个需求,要求微信小程序换头像,用户剪裁图片必须是圆形,也在github上看了一些例子,通常剪裁图片用的都是方形,因此本身打算写一个小组件,能够把图片剪裁成圆形,主要思路就是使用canvas绘图,把剪裁的图片绘制成圆形,另外剪裁图片的窗口还能够移动放大缩小,这个功能就用了微信组件movable-view,好了,该说的也说完了,下面我们开始撸代码。
javascript
可移动的视图容器,在页面中能够拖拽滑动 会有好多个属性,在这里不一一介绍,只说咱们能用到的就能够。 咱们用到的属性主要有:
html
画布。该组件是原生组件能够绘制图像,分享朋友圈生成海报就常常用到这个属性,就简单的说下:
在wxml中必需要有canvas这个标签,才能够绘制图像,并且要有canvas-id属性,表明canvas 组件的惟一标识符,还有许多API我就不一一介绍了,底下用的API代码当中都会用注释。详情请看微信小程序画布APIhttps://developers.weixin.qq.com/miniprogram/dev/api/canvas/wx.canvasGetImageData.htmljava
index.wxml
Tip: 必须把canvas放到引入剪裁组件的wxml中,不然绘制不成功,由于canvas是原生组件脱离在 WebView 渲染流程外。
git
<view class="container"> <button wx:if="{{!imgSrc}}" bindtap="getImgurl"> 选择图片 </button> <view class="clip-box" wx:if="{{imgSrc}}"> <ClipImg imgSrc="{{imgSrc}}"></ClipImg> </view> </view> <canvas canvas-id="myCanvas" style="position:absolute; width:100%;height:100%;border: 1px solid red;left: -9999px; top: -9999px;"></canvas> 复制代码
index.json引入截取图片的组件
github
{
"component": true,
"usingComponents": {
"ClipImg": "../../component/clipImg/clipImg"
}
}
复制代码
index.js上传图片显示
json
const app = getApp()
Page({
data: {
imgSrc: ''
},
//选择图片
getImgurl: function () {
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 能够指定是原图仍是压缩图,默认两者都有
sourceType: ['album', 'camera'], // 能够指定来源是相册仍是相机,默认两者都有
success: (res) => {
// 返回选定照片的本地文件路径列表,tempFilePath能够做为img标签的src属性显示图片
const tempFilePaths = res.tempFilePaths;
//启动上传等待中...
wx.showToast({
title: '正在上传...',
icon: 'loading',
mask: true,
duration: 1000
})
this.setData({
imgSrc: res.tempFilePaths
})
}
})
},
onLoad: function () {
}
})
复制代码
接下来就是剪裁图片组件的封装
canvas
首先是页面布局,也就是clipImg.wxml
小程序
<view class="clip"> <image class="head-img" style="width:{{cropperW}}rpx;height:{{cropperH}}rpx" src="{{imageUrl}}"></image> <movable-area scale-area style="width:{{cropperW}}rpx;height:{{cropperH}}rpx"> <movable-view bindchange="move" bindscale="scale" direction="all" scale scale-min="0.5" scale-max="1.8"> </movable-view> </movable-area> <view class="btn"> <text bindtap="cancel">取消</text> <text bindtap="getImageInfo">保存</text> </view> </view> 复制代码
大概就是这个样子微信小程序
上边的圆就是截取就是截取框。
而后就是clipImg.js文件主要就是对图片截取的一些操做
api
Component({
/** * 组件的属性列表 */
properties: {
imgSrc: {
type: 'String',
value: ''
}
},
/** * 组件的初始数据 * imageUrl string 初始化图片 * cropperW string 缩小图宽度 * cropperH string 缩小图高度, * img_ratio string 图片比例, * IMG_W string 原图高度, * IMG_H string 原图高度, * left string 图片距离左边距离, * top string 图片距离上边距离, * clipW number 默认截取框 */
data: {
imageUrl: '',
cropperW: '',
cropperH: '',
img_ratio: '',
IMG_W: '',
IMG_H: '',
left: '',
top: '',
clipW: 200
},
/** * 组件的方法列表 */
methods: {
//点击取消
cancel: function () {
var myEventDetail = {} // detail对象,提供给事件监听函数
var myEventOption = {} // 触发事件的选项
this.triggerEvent('myevent', myEventDetail, myEventOption)
},
//拖拽事件
move: function ({ detail }) {
this.setData({
left: detail.x * 2,
top: detail.y * 2
})
},
//缩放事件
scale: function ({ detail }) {
console.log(detail.scale)
this.setData({
clipW: 200 * detail.scale
})
},
//生成图片
getImageInfo: function () {
wx.showLoading({
title: '图片生成中...',
})
const img_ratio = this.data.img_ratio;
//要截取canvas的宽
const canvasW = (this.data.clipW / this.data.cropperW) * this.data.IMG_W
//要截取canvas的高
const canvasH = (this.data.clipW / this.data.cropperH) * this.data.IMG_H
//要截取canvas到左边距离
const canvasL = (this.data.left / this.data.cropperW) * this.data.IMG_W
//要截取canvas到上边距离
const canvasT = (this.data.top / this.data.cropperH) * this.data.IMG_H
// 将图片写入画布
const ctx = wx.createCanvasContext('myCanvas');
//绘制图像到画布
ctx.save(); // 先保存状态 已便于画完圆再用
ctx.beginPath(); //开始绘制
ctx.clearRect(0, 0, 1000, 1000)
//先画个圆
ctx.arc(this.data.clipW / 2, this.data.clipW / 2, this.data.clipW / 2, 0, 2 * Math.PI, false)
ctx.clip();//画了圆 再剪切 原始画布中剪切任意形状和尺寸。一旦剪切了某个区域,则全部以后的绘图都会被限制在被剪切的区域内
ctx.drawImage(this.data.imageUrl, canvasL, canvasT, canvasW, canvasH, 0, 0, this.data.clipW, this.data.clipW); // 推动去图片
ctx.restore(); //恢复以前保存的绘图上下文 恢复以前保存的绘图上下午即状态 能够继续绘制
ctx.draw(true, () => {
// 获取画布要裁剪的位置和宽度
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: this.data.clipW,
height: this.data.clipW,
destWidth: this.data.clipW,
destHeight: this.data.clipW,
quality: 0.5,
canvasId: 'myCanvas',
success: (res) => {
wx.hideLoading()
/** * 截取成功后能够上传的服务端直接调用 * wx.uploadFile(); */
//成功得到地址的地方
wx.previewImage({
current: '', // 当前显示图片的http连接
urls: [res.tempFilePath] // 须要预览的图片http连接列表
})
}
})
})
}
},
ready: function () {
this.setData({
imageUrl: this.data.imgSrc[0]
})
//获取图片宽高
wx.getImageInfo({
src: this.data.imageUrl,
success: (res) => {
console.log('图片信息', res);
//图片实际款高
const width = res.width;
const height = res.height;
//图片宽高比例
const img_ratio = width / height
this.setData({
img_ratio,
IMG_W: width,
IMG_H: height,
})
if (img_ratio >= 1) {
//宽比较大,横着显示
this.setData({
cropperW: 750,
cropperH: 750 / img_ratio,
})
} else {
//竖着显示
this.setData({
cropperW: 750 * img_ratio,
cropperH: 750
})
}
}
})
}
})
复制代码
到如今为止一个截取图片就完成了,可能会有些问题,好比截取的图片的框没有居中,本身能够再次封装这个组件,由于如今已经适合咱们公司本身项目了。咱们来预览下。另外这个组件支持双指放大截取框来截取图片,不过微信开发者工具不能展现,本身能够把代码下载下来,在本身手机上扫码查看效果。
另外我把项目放到了github上边,但愿小哥哥小姐姐们多多点赞,多多支持。使用的时候直接把component里边的组件直接引进去就行,有什么疑问能够在github底下留言问我,谢谢。点赞的小哥哥小姐姐最可爱,哈哈哈。。。