# Get distance between two finger on mediapipe using javascript with regards to z position

I am trying to detect if the tip of thumb and index finger has touched each other. But I am not sure if I am doing this correctly.

``````const hand = result.multiHandLandmarks; //Returns {x,y,z} of each landmark.
//hand is the tip of the thumb  - Returns {x,y,z} of the tip of thumb.
//hand is the tip of the index finger - Returns {x,y,z} of the tip of index finger.

//I don't know exactly if I am doing this right to get the distance between two tip of fingers.
const x = hand.x - hand.x;
const y = hand.y - hand.y;
const z = hand.z;

const distance = Math.sqrt(x * x + y * y);

const element = document.getElementById("card")

//--Here I want to check if the user's index and thumb finger is touching each other.
//if it is, then move the element based on the position of index finger.

``````

I have tried doing it this way, but it seems like not the best way to do it.

``````
//I'm not sure about 0.045, if it's enough distance to detect a touch between two finger.
if (distance <= 0.045) {
element.style.left = `\${indexFinger.x - element.offsetWidth / 2}px`;
element.style.top = `\${indexFinger.y - element.offsetHeight / 2}px`;
console.log("grabbing");
} else {
console.log("NOT Grabbing", distance, z);
}

``````

Also I want to consider the Z position of index finger, if the hand is too close to the camera, then I want to popup some alert to notify the user to move his hand away in a perfect position. Because I think, the X and Y depends on the Z position. If a hand is too close to the camera the x and y returns higher number.

Posted on Categories javascript