前言
最近在開發小程序,產品經理提了一個需求,要求微信小程序換頭像,用戶剪裁圖片必須是圓形,也在github上看了一些例子,一般剪裁圖片用的都是方形,所以自己打算寫一個小組件,可以把圖片剪裁成圓形,主要思路就是使用canvas繪圖,把剪裁的圖片繪制成圓形,另外剪裁圖片的窗口還可以移動放大縮小,這個功能就用了微信組件movable-view,好了,該說的也說完了,下面咱們開始擼代碼。
movable-view組件
可移動的視圖容器,在頁面中可以拖拽滑動
會有好多個屬性,在這里不一一介紹,只說我們能用到的就可以。
我們用到的屬性主要有:
1.direction:movable-view的移動方向,屬性值有all、vertical、horizontal、none
2.scale:是否支持雙指縮放,默認縮放手勢生效區域是在movable-view內
3.scale-min 定義縮放倍數最小值
4.scale-max 定義縮放倍數最大值
5.bindchange 拖動過程中觸發的事件,event.detail = {x: x, y: y, source: source},其中source表示產生移動的原因,值可為touch(拖動)、touch-out-of-bounds(超出移動范圍)、out-of-bounds(超出移動范圍后的回彈)、friction(慣性)和空字符串(setData)
6.bindscale 縮放過程中觸發的事件,event.detail = {x: x, y: y, scale: scale},其中x和y字段在2.1.0之后開始支持返回
主要用到的就是這幾個值
另外使用movable-view的時候必須在外邊加一個movable-area的父元素,不然的話沒有移動區域。
movable-view 的可移動區域,屬性只有:
scale-area 當里面的movable-view設置為支持雙指縮放時,設置此值可將縮放手勢生效區域修改為整個movable-area,是個boolean值,默認false
截取區域的移動已經說完了,詳情請看傳送門
canvas繪圖
畫布。該組件是原生組件可以繪制圖像,分享朋友圈生成海報就經常用到這個屬性,就簡單的說下:
在wxml中必須要有canvas這個標簽,才可以繪制圖像,而且要有canvas-id屬性,代表canvas 組件的唯一標識符,
還有許多API我就不一一介紹了,底下用的API代碼當中都會用注釋。詳情請看微信小程序畫布API傳送門
代碼實現
1.首先是選擇圖片
wxml就是初始化一個按鈕點擊的時候選擇圖片,而且需要引入我們封裝的截取圖片組件,并把圖片作為參數傳進去,封裝組件方法請看我另一篇文章組件封裝
index.wxml
Tip: 必須把canvas放到引入剪裁組件的wxml中,否則繪制不成功,因為canvas是原生組件脫離在 WebView 渲染流程外。
<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引入截取圖片的組件
{ "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文件主要就是對圖片截取的一些操作
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上問我,謝謝。點贊的小哥哥小姐姐最可愛,哈哈哈。。。
項目地址鏈接描述
推薦:
感興趣的朋友可以關注小編的微信公眾號【碼農那點事兒】,更多網頁制作特效源碼及學習干貨哦!!!
總結
以上所述是小編給大家介紹的微信小程序之裁剪圖片成圓形的實現代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VEVB武林網網站的支持!
新聞熱點
疑難解答