akalenuk / wordsandbuttons

A growing collection of interactive tutorials, demos, and quizzes about maths, algorithms, and programming.
https://wordsandbuttons.online
The Unlicense
486 stars 18 forks source link

Support touch events #17

Closed redblobgames closed 3 years ago

redblobgames commented 3 years ago

In the past if you wanted to support touch events for tablet/phone/windows10 you would have to implement a separate set of events, sometimes different per browser. But now we have pointer events, and it looks like it's relatively easy to support and widely supported.

I take https://wordsandbuttons.online/lagrange_polynomial_as_a_gateway_drug_to_basis_splines.html as an example page.

  1. Change mousemove to pointermove, mousedown to pointerdown, mouseleave to pointerleave. The pointer events support both mouse and touch so it will continue working with mouse.
  2. Add CSS canvas { touch-action: none; } to disable the browser's default touch-drag handlers (like dragging an image, or scrolling the page). This will not affect mouse users.
  3. Add either i_canvas.setPointerCapture(e.pointerId) or i_canvas.releasePointerCapture(e.pointerId) inside the pointerdown event handler. This tells the browser to either hold on to the drag until you let go, or to release it when you leave the canvas. It looks like for this page you want to release it.

With these three changes, your page will work with touch events.

akalenuk commented 3 years ago

Thank you so much for bringing this up! And for your help!

I've patched the Lagrange thing right now, it should not work on your phone as intended :-) I'll start tinkering with the rest a bit later today, it looks like 80% of the work is scriptable, I'll just have to retest the pages to see if the capture thing and pointerleave work adequately.

By the way, I also found a performance bug by simply running the Lagrangian page on my phone. Apparently, I forgot to turn off the animations which are... not there anyway :-) So this exercise turned out to be 2x helpful.

Thanks again! You are the best!

akalenuk commented 3 years ago

Finished all the pages! Well, I only tested in on one device so there might be still bugs, but conceptually it works!

I'm actually surprised how smooth it went. A few bugs came up, and a few layout issues, and I'm happy I caught them all in one go and not one-by-one. But indeed, simply changing the mouse to pointer, and putting no action on touch, did the trick on most pages without any further effort :-) Amazing!

Thank you once again!