How do I find the distance from the touch center?
For example, we touch and if we pull up we get 1 2 3. If we pull down, we get -1 -2 -3.
I know it's possible to do it with a saved position (start touch). But I can't think about it myself. Thank you!
// touchstart
window.addEventListener('touchmove', touchmove);
var deltaY;
function touchmove(e) {
deltaY = e.touches[0].clientY;
console.log(deltaY);
}
You can create 2 event listeners, one for capturing the start position, another for capturing the move events:
document.body.addEventListener('touchmove', touchmove);
document.body.addEventListener('touchstart', touchstart);
var startX, startY;
function touchstart(e)
{
startX = e.touches[0].clientX;
startY = e.touches[0].clientY;
}
function touchmove(e)
{
var deltaX = e.touches[0].clientX - startX,
deltaY = e.touches[0].clientY - startY;
console.log('Delta x,y',deltaX, deltaY);
}
Example HTML:
var startX, startY;
function touchstart(e)
{
startX = e.touches[0].clientX;
startY = e.touches[0].clientY;
}
function touchmove(e)
{
var deltaX = e.touches[0].clientX - startX, deltaY = e.touches[0].clientY - startY;
console.log('Distance:', Math.sqrt((deltaX ** 2) + (deltaY ** 2)));
start_box = document.querySelector(".start");
end_box = document.querySelector(".end");
start_box.style.setProperty("display", "initial");
end_box.style.setProperty("display", "initial");
start_box.style.setProperty("position", "absolute");
end_box.style.setProperty("position", "absolute");
start_box.style.setProperty("top", `${startY}px`);
start_box.style.setProperty("left", `${startX}px`);
end_box.style.setProperty("top", `${startY + deltaY}px`);
end_box.style.setProperty("left", `${startX + deltaX}px`);
}
//window.onload = function()
//{
// document.querySelector("body").addEventListener('touchmove', touchmove);
// document.querySelector("body").addEventListener('touchstart', touchstart);
//}
window.addEventListener('touchstart', touchstart);
window.addEventListener('touchmove', touchmove);
.start
{
background-color: green;
width: 10px;
height: 10px;
display: none;
}
.end
{
background-color: red;
width: 10px;
height: 10px;
display: none;
}
<div class="start">
</div>
<div class="end">
</div>