The web keeps growing and getting more sophisticated. As a result, more support is being poured into the web, giving it the ability to do things native to the operating system.
In this shot, we look into the Touch API.
This API enables us to register touch events on our webpage. These touch events are fired by mobile devices with touch screens, trackball, and stylus.
Android/iOS mobile devices are used more often to visit websites than desktops and laptops nowadays. However, the events in DOM are mostly for desktops. This API now brings the touch feel to the web, so developers can register events ideal to mobile devices.
The touch events in the Touch API are:
touchstart
: This event is fired when a finger is placed on the screen.
touchend
: This event is fired when a finger is removed from the screen.
touchcancel
: This event is fired when a finger’s touch or movement is interrupted.
touchmove
: This event is fired when a finger is dragged across the screen.
Touch events are ideal for building a drawing app as a progressive web app (PWA). We can get the canvas DOM instance and use the addEventListener
API to register the touch events to the canvas.
canvas.addEventListener("touchstart", ()=> {
console.log("touch start")
})
This event will be fired when the canvas
element is touched. So the callback will log "touch start"
.
canvas.addEventListener("touchmove", ()=> {
console.log("touch move")
})
The code above will fire the callback when the canvas
element is touched and this touch is also moved on the element.
canvas.addEventListener("touchend", ()=> {
console.log("touch end")
})
This callback will be fired when the canvas
element is touched on and the movement on the element is removed.
canvas.addEventListener("touchcancel", ()=> {
console.log("touch cancel")
})
The callback in the code above will be fired when the touch event on the canvas
is canceled.
Play with a live demo here.
To learn more about the Touch API, visit this link.