最近在開發小程序,產品經理提了一個需求,要求微信小程序換頭像,用戶剪裁圖片必須是圓形,也在github上看了一些例子,通常剪裁圖片用的都是方形,因此本身打算寫一個小組件,能夠把圖片剪裁成圓形,主要思路就是使用canvas繪圖,把剪裁的圖片繪製成圓形,另外剪裁圖片的窗口還能夠移動放大縮小,這個功能就用了微信組件movable-view,好了,該說的也說完了,下面我們開始擼代碼。html
可移動的視圖容器,在頁面中能夠拖拽滑動
會有好多個屬性,在這裏不一一介紹,只說咱們能用到的就能夠。
咱們用到的屬性主要有:git
畫布。該組件是原生組件能夠繪製圖像,分享朋友圈生成海報就常常用到這個屬性,就簡單的說下:
在wxml中必需要有canvas這個標籤,才能夠繪製圖像,並且要有canvas-id屬性,表明canvas 組件的惟一標識符,
還有許多API我就不一一介紹了,底下用的API代碼當中都會用註釋。詳情請看微信小程序畫布API傳送門github
index.wxml
Tip: 必須把canvas放到引入剪裁組件的wxml中,不然繪製不成功,由於canvas是原生組件脫離在 WebView 渲染流程外。json
<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引入截取圖片的組件canvas
{ "component": true, "usingComponents": { "ClipImg": "../../component/clipImg/clipImg" } }
index.js上傳圖片顯示小程序
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 () { } })
接下來就是剪裁圖片組件的封裝
首先是頁面佈局,也就是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上邊,但願小哥哥小姐姐們多多點贊,多多支持,有什麼疑問能夠在github上問我,謝謝。點讚的小哥哥小姐姐最可愛,哈哈哈。。。
項目地址連接描述微信開發