Quick Touch Events
// no scrolling on mobile
document.addEventListener("touchmove", e => e.preventDefault(), {
passive: false
});
// has more than one touch point
const hasTouch =
navigator.maxTouchPoints != null && navigator.maxTouchPoints > 0;
function touchify(e) {
const touch = [];
touch.x = touch.y = 0;
if (e.touches != null && e.touches.length > 0) {
touch.x = e.touches[0].clientX;
touch.y = e.touches[0].clientY;
for (let i = 0; i < e.touches.length; i++) {
touch[i] = e.touches[i];
}
} else {
touch.x = e.clientX;
touch.y = e.clientY;
touch[0] = { clientX: e.clientX, clientY: e.clientY };
}
return touch;
}
let clickOrTouchEnd,
downOrTouchStart,
enterOrTouchStart,
moveOrTouchMove,
upOrTouchEnd,
leaveOrTouchEnd;
if (hasTouch) {
clickOrTouchEnd = "touchend";
downOrTouchStart = "touchstart";
enterOrTouchStart = "touchstart";
moveOrTouchMove = "touchmove";
upOrTouchEnd = "touchend";
leaveOrTouchEnd = "touchend";
} else {
clickOrTouchEnd = "click";
downOrTouchStart = "mousedown";
enterOrTouchStart = "mouseenter";
moveOrTouchMove = "mousemove";
upOrTouchEnd = "mouseup";
leaveOrTouchEnd = "mouseleave";
}
function dot(x, y, radius, color) {
const el = document.createElement("div");
const size = `${radius * 2}px`;
Object.assign(el.style, {
position: "absolute",
left: `${x}px`,
top: `${y}px`,
width: size,
height: size,
transform: `translate(${-radius}px, ${-radius}px)`,
borderRadius: "50%",
background: color
});
el.classList.add("dot");
document.body.appendChild(el);
return el;
}
let down = false;
let lastTouch;
document.addEventListener(downOrTouchStart, e => {
const { x, y } = touchify(e);
dot(x, y, 30, `rgba(255, 0, 0, 0.2)`);
down = true;
});
document.addEventListener(moveOrTouchMove, e => {
if (down) {
const touches = touchify(e);
// draw more than one touch
for (let i = 0; i < touches.length; i++) {
const touch = touches[i];
dot(touch.clientX, touch.clientY, 10, `rgba(0, 0, 155, 0.2)`);
}
lastTouch = touches[0];
}
});
document.addEventListener(upOrTouchEnd, e => {
if (down) {
dot(lastTouch.clientX, lastTouch.clientY, 20, `rgba(0, 155, 0, 0.2)`);
down = false;
}
});
Draw with your mouse by clicking, holding down and dragging…
I often use some variation of this depending on the project… This snippet normalizes touch events in a simple way, prevents scrolling and gives an example of how to handle multi-touch.
You’ll probably want a to use a meta tag like this – for the full effect.
<meta name="viewport" content="width=device-width, initial-scale=1.0">