/scalajs-pointer-events-polyfill

A Scala.js facade for the Pointer Events Polyfill (https://github.com/jquery/PEP) library.

Primary LanguageJavaScriptMIT LicenseMIT

scalajs-pointer-events-polyfill

A Scala.js facade for Pointer Events Polyfill. Pointer Events provide a common interface for handling different pointing devices (mouse, touch, pen, etc.). They're not supported by many browsers yet, hence the need for a polyfill.

Here's a little demo racing game that uses it: scalajs-racer.

Usage

Add the following to your build.sbt:

resolvers += Resolver.bintrayRepo("sammthomson", "maven")
libraryDependencies += "org.samthomson" %%% "scalajs-pointer-events-polyfill" % "0.1"

Then you can attach a pointer event listener like so:

import org.samthomson.pointerevents.{PointerEvent, PointerEventTarget}
import org.scalajs.dom.{document, console}
import scala.scalajs.js.JSApp

object Example extends JSApp {
  def main(): Unit = {
    val canvas = document.getElementById("canvas")
    canvas.onPointerDown { (e: PointerEvent) => console.log(e.clientX + ", " + e.clientY) }
  }
}

You'll want your html element to have a touch-action="none" attribute, e.g.:

<html>
  <body>
    <canvas id="canvas" width="710" height="562" touch-action="none"></canvas>
  </body>
  <script type="text/javascript" src="./target/scala-2.11/example-jsdeps.js"></script>
  <script type="text/javascript" src="./target/scala-2.11/example-opt.js"></script>
  <script type="text/javascript">
    Example().main();
  </script>
</html>

PointerEventTarget is an implicit class that adds the following methods to any org.scalajs.dom.raw.EventTarget (which includes HTMLElements):

def onPointerDown(f: js.Function1[PointerEvent, _]): Unit
def onPointerUp(f: js.Function1[PointerEvent, _]): Unit
def onPointerMove(f: js.Function1[PointerEvent, _]): Unit
def onPointerOver(f: js.Function1[PointerEvent, _]): Unit
def onPointerOut(f: js.Function1[PointerEvent, _]): Unit
def onPointerEnter(f: js.Function1[PointerEvent, _]): Unit
def onPointerLeave(f: js.Function1[PointerEvent, _]): Unit
def onPointerCancel(f: js.Function1[PointerEvent, _]): Unit
def onGotPointerCapture(f: js.Function1[PointerEvent, _]): Unit
def onLostPointerCapture(f: js.Function1[PointerEvent, _]): Unit