class Pinch { constructor(element) { this.event_cache = []; this.onpinch = () => {}; this.onfinish = () => {}; this.onstart = () => {}; element.onpointerdown = (e) => this.pointer_down_handler(e); element.onpointermove = (e) => this.pointer_move_handler(e); element.onpointerup = (e) => this.pointer_up_handler(e); element.onpointercancel = (e) => this.pointer_up_handler(e); element.onpointerout = (e) => this.pointer_up_handler(e); element.onpointerleave = (e) => this.pointer_up_handler(e); } pointer_down_handler(event) { this.event_cache.push(event); if (this.event_cache.length === 2) { const diff = Math.hypot( this.event_cache[0].clientX - this.event_cache[1].clientX, this.event_cache[0].clientY - this.event_cache[1].clientY, ); const point = { x: (this.event_cache[0].clientX + this.event_cache[1].clientX) / 2, y: (this.event_cache[0].clientY + this.event_cache[1].clientY) / 2, }; this.onstart({ point, distance: diff }); } } pointer_move_handler(event) { const index = this.event_cache.findIndex( (cached) => cached.pointerId == event.pointerId, ); this.event_cache[index] = event; if (this.event_cache.length === 2) { const diff = Math.hypot( this.event_cache[0].clientX - this.event_cache[1].clientX, this.event_cache[0].clientY - this.event_cache[1].clientY, ); const point = { x: (this.event_cache[0].clientX + this.event_cache[1].clientX) / 2, y: (this.event_cache[0].clientY + this.event_cache[1].clientY) / 2, }; this.onpinch({ distance: diff, point }); } } pointer_up_handler(event) { let cleanup = false; const ev = {}; if (this.event_cache.length === 2) { ev['distance'] = Math.hypot( this.event_cache[0].clientX - this.event_cache[1].clientX, this.event_cache[0].clientY - this.event_cache[1].clientY, ); ev['point'] = { x: (this.event_cache[0].clientX + this.event_cache[1].clientX) / 2, y: (this.event_cache[0].clientY + this.event_cache[1].clientY) / 2, }; cleanup = true; } const index = this.event_cache.findIndex( (cached) => cached.pointerId === event.pointerId, ); this.event_cache.splice(index, 1); if (cleanup) { this.onfinish(ev); } } }