前言
最近需要使用手指捏合擴(kuò)大的手勢(shì)操作,找了幾個(gè)組件,要么對(duì) Vue 適配不好,要么量級(jí)太大,決定自己手寫(xiě)手勢(shì)操作。
思路
直接在 DOM 上綁定 touchstart 、touchmove、touchend 不僅要綁定這幾個(gè)事件,而且用在其他項(xiàng)目還不好復(fù)用。所以用 Vue 自定義指令比較合適,指令還可以封裝成插件,再使用 npm 托管,這樣隨時(shí)隨地都可以使用了。
Vue 自定義指令
Vue 官網(wǎng)就有 自定義指令 的教程,摘取我們需要的關(guān)鍵代碼。
Vue.directive('pinch', { // 只調(diào)用一次,指令第一次綁定到元素時(shí)調(diào)用
bind (el, binding) { // el:指令所綁定的元素,可以用來(lái)直接操作 DOM
// binding.value():運(yùn)行添加到指令的回調(diào)方法
}
})多點(diǎn)觸控
實(shí)現(xiàn)捏合手勢(shì),必然是多根手指操作,因此使用 touch 的多點(diǎn)觸控,就可以拿到多個(gè)觸控點(diǎn)的位置了。再通過(guò)判斷兩點(diǎn) touchstart 與 touchend 前的距離偏差,就可以判斷出是捏合手勢(shì),還是放大手勢(shì)了。關(guān)鍵代碼如下
let touchFlag = false;let touchInitSpacing = 0;let touchNowSpacing = 0;
el.addEventListener('touchstart',(e)=>{
if(e.touches.length>1){
touchFlag = true;
touchInitSpacing = Math.sqrt((e.touches[0].clientX-e.touches[1].clientX)**2 +(e.touches[1].clientY-e.touches[1].clientY)**2);
}else{
touchFlag = false;
}
});
el.addEventListener('touchmove',(e)=>{
if(e.touches.length>1&&touchFlag){
touchNowSpacing = Math.sqrt((e.touches[0].clientX-e.touches[1].clientX)**2 +(e.touches[1].clientY-e.touches[1].clientY)**2);
}
});
el.addEventListener('touchend',()=>{
if(touchFlag){
touchFlag = false;
if(touchInitSpacing-touchNowSpacing>0){
binding.value('pinchin');
}else{
binding.value('pinchout');
}
}
});使用指令
手勢(shì)邏輯寫(xiě)入自定義指令,就可以直接使用了。
<template><p class="pinch" v-pinch="pinchCtrl"></p></template>
new Vue({
methods: {
pinchCtrl: function (e) {
if(e==='pinchin'){
console.log('捏合')
}
if(e==='pinchout'){
console.log('擴(kuò)大');
}
}
}
})總結(jié)
使用 Vue 自定義指令完成手勢(shì)操作并不復(fù)雜,同時(shí)將該邏輯封裝成組件量級(jí)很輕。
組件源碼
點(diǎn)此 查看完整源碼。
使用該組件
如果該組件對(duì)你有所幫助,可以通過(guò) npm 的方式進(jìn)行安裝:
npm i vue-pinch --save
更多組件
create-picture:該組件提供了 canvas 的圖片繪制與文本繪制功能,使用同步的語(yǔ)法完成異步繪制,簡(jiǎn)化原生 canvas 繪制語(yǔ)法。







