Recently, I need to use the gesture operation of pinching and expanding with fingers. I have found several components, but they are either not suitable for Vue or the magnitude is too large. I decided to Operate with your own handwriting gestures.
Bind directly on the DOM touchstart
, touchmove
, touchend
It is not only necessary to bind these events , and it is not easy to reuse it in other projects. Therefore, it is more appropriate to use Vue custom instructions. The instructions can also be encapsulated into plug-ins and then hosted using npm
, so that they can be used anytime and anywhere.
Vue official website has a tutorial on custom instructions, extracting the key codes we need.
Vue.directive('pinch', { // 只调用一次,指令第一次绑定到元素时调用 bind (el, binding) { // el:指令所绑定的元素,可以用来直接操作 DOM // binding.value():运行添加到指令的回调方法 } })复制代码
To realize the pinch gesture, it must be operated by multiple fingers, so using the multi-touch of touch
, you can get multiple touches The location of the control point. Then by judging the distance deviation between the two points touchstart
and touchend
, you can determine whether it is a pinch gesture or an enlargement gesture. The key code is as follows:
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'); } } });复制代码
Write custom instructions with gesture logic, and you can use it directly.
<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('扩大'); } } } })复制代码
It is not complicated to use Vue custom instructions to complete gesture operations, and at the same time, encapsulating the logic into components is very lightweight.
Click here to view the complete source code.
If this component is helpful to you, you can install it through npm:
npm i vue-pinch --save复制代码
create- picture: This component provides canvas picture drawing and text drawing functions, uses synchronous syntax to complete asynchronous drawing, and simplifies the native canvas drawing syntax.
Recommended tutorial: "JS Tutorial"
The above is the detailed content of Vue gesture component tutorial. For more information, please follow other related articles on the PHP Chinese website!