diff options
Diffstat (limited to 'files/vi/web/api/touch_events/index.html')
-rw-r--r-- | files/vi/web/api/touch_events/index.html | 340 |
1 files changed, 340 insertions, 0 deletions
diff --git a/files/vi/web/api/touch_events/index.html b/files/vi/web/api/touch_events/index.html new file mode 100644 index 0000000000..f723a4f971 --- /dev/null +++ b/files/vi/web/api/touch_events/index.html @@ -0,0 +1,340 @@ +--- +title: Touch events +slug: Web/API/Touch_events +tags: + - Advanced + - DOM + - Event + - Guide + - Mobile + - NeedsTranslation + - Overview + - TopicStub + - touch +translation_of: Web/API/Touch_events +--- +<div>{{DefaultAPISidebar("Touch Events")}}</div> + +<p><span class="seoSummary">In order to provide quality support for touch-based user interfaces, touch events offer the ability to interpret finger (or stylus) activity on touch screens or trackpads.</span></p> + +<p>The touch events interfaces are relatively low-level APIs that can be used to support application specific multi-touch interactions such as a two-finger gesture. A multi-touch interaction starts when a finger (or stylus) first touches the contact surface. Other fingers may subsequently touch the surface and optionally move across the touch surface. The interaction ends when the fingers are removed from the surface. During this interaction, an application receives touch events during the start, move and end phases.</p> + +<p>Touch events are similar to mouse events except they support simultaneous touches and at different locations on the touch surface. The {{domxref("TouchEvent")}} interface encapsulates all of the touch points that are currently active. The {{domxref("Touch")}} interface, which represents a single touch point, includes information such as the position of the touch point relative to the browser viewport.</p> + +<h2 id="Definitions">Definitions</h2> + +<dl> + <dt>Surface</dt> + <dd>The touch-sensitive surface. This may be a screen or trackpad.</dd> +</dl> + +<dl> + <dt>Touch point</dt> + <dd>A point of contact with the surface. This may be a finger (or elbow, ear, nose, whatever, but typically a finger) or stylus.</dd> +</dl> + +<h2 id="Interfaces">Interfaces</h2> + +<dl> + <dt>{{domxref("TouchEvent")}}</dt> + <dd>Represents an event that occurs when the state of touches on the surface changes.</dd> + <dt>{{domxref("Touch")}}</dt> + <dd>Represents a single point of contact between the user and the touch surface.</dd> + <dt>{{domxref("TouchList")}}</dt> + <dd>Represents a group of touches; this is used when the user has, for example, multiple fingers on the surface at the same time.</dd> +</dl> + +<h2 id="Example">Example</h2> + +<p>This example tracks multiple touch points at a time, allowing the user to draw in a {{HTMLElement("canvas")}} with more than one finger at a time. It will only work on a browser that supports touch events.</p> + +<div class="note"><strong>Note:</strong> The text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus or other contact method.</div> + +<h3 id="Create_a_canvas">Create a canvas</h3> + +<pre class="brush: html"><canvas id="canvas" width="600" height="600" style="border:solid black 1px;"> + Your browser does not support canvas element. +</canvas> +<br> +<button onclick="startup()">Initialize</button> +<br> +Log: <pre id="log" style="border: 1px solid #ccc;"></pre> +</pre> + +<h3 id="Setting_up_the_event_handlers">Setting up the event handlers</h3> + +<p>When the page loads, the <code>startup()</code> function shown below should be called by our {{HTMLElement("body")}} element's <code>onload</code> attribute (but in the example we use a button to trigger it, due to limitations of the MDN live example system).</p> + +<pre class="brush: js">function startup() { + var el = document.getElementsByTagName("canvas")[0]; + el.addEventListener("touchstart", handleStart, false); + el.addEventListener("touchend", handleEnd, false); + el.addEventListener("touchcancel", handleCancel, false); + el.addEventListener("touchmove", handleMove, false); + console.log("initialized."); +} +</pre> + +<p>This simply sets up all the event listeners for our {{HTMLElement("canvas")}} element so we can handle the touch events as they occur.</p> + +<h4 id="Tracking_new_touches">Tracking new touches</h4> + +<p>We'll keep track of the touches in-progress.</p> + +<pre class="brush: js">var ongoingTouches = []; +</pre> + +<p>When a {{event("touchstart")}} event occurs, indicating that a new touch on the surface has occurred, the <code>handleStart()</code> function below is called.</p> + +<pre class="brush: js">function handleStart(evt) { + evt.preventDefault(); + console.log("touchstart."); + var el = document.getElementsByTagName("canvas")[0]; + var ctx = el.getContext("2d"); + var touches = evt.changedTouches; + + for (var i = 0; i < touches.length; i++) { + console.log("touchstart:" + i + "..."); + ongoingTouches.push(copyTouch(touches[i])); + var color = colorForTouch(touches[i]); + ctx.beginPath(); + ctx.arc(touches[i].pageX, touches[i].pageY, 4, 0, 2 * Math.PI, false); // a circle at the start + ctx.fillStyle = color; + ctx.fill(); + console.log("touchstart:" + i + "."); + } +} +</pre> + +<p>This calls {{domxref("event.preventDefault()")}} to keep the browser from continuing to process the touch event (this also prevents a mouse event from also being delivered). Then we get the context and pull the list of changed touch points out of the event's {{domxref("TouchEvent.changedTouches")}} property.</p> + +<p>After that, we iterate over all the {{domxref("Touch")}} objects in the list, pushing them onto an array of active touch points and drawing the start point for the draw as a small circle; we're using a 4-pixel wide line, so a 4 pixel radius circle will show up neatly.</p> + +<h4 id="Drawing_as_the_touches_move">Drawing as the touches move</h4> + +<p>Each time one or more fingers moves, a {{event("touchmove")}} event is delivered, resulting in our <code>handleMove()</code> function being called. Its responsibility in this example is to update the cached touch information and to draw a line from the previous position to the current position of each touch.</p> + +<pre class="brush: js">function handleMove(evt) { + evt.preventDefault(); + var el = document.getElementsByTagName("canvas")[0]; + var ctx = el.getContext("2d"); + var touches = evt.changedTouches; + + for (var i = 0; i < touches.length; i++) { + var color = colorForTouch(touches[i]); + var idx = ongoingTouchIndexById(touches[i].identifier); + + if (idx >= 0) { + console.log("continuing touch "+idx); + ctx.beginPath(); + console.log("ctx.moveTo(" + ongoingTouches[idx].pageX + ", " + ongoingTouches[idx].pageY + ");"); + ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY); + console.log("ctx.lineTo(" + touches[i].pageX + ", " + touches[i].pageY + ");"); + ctx.lineTo(touches[i].pageX, touches[i].pageY); + ctx.lineWidth = 4; + ctx.strokeStyle = color; + ctx.stroke(); + + ongoingTouches.splice(idx, 1, copyTouch(touches[i])); // swap in the new touch record + console.log("."); + } else { + console.log("can't figure out which touch to continue"); + } + } +} +</pre> + +<p>This iterates over the changed touches as well, but it looks in our cached touch information array for the previous information about each touch in order to determine the starting point for each touch's new line segment to be drawn. This is done by looking at each touch's {{domxref("Touch.identifier")}} property. This property is a unique integer for each touch, and remains consistent for each event during the duration of each finger's contact with the surface.</p> + +<p>This lets us get the coordinates of the previous position of each touch and use the appropriate context methods to draw a line segment joining the two positions together.</p> + +<p>After drawing the line, we call <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice"><code>Array.splice()</code></a> to replace the previous information about the touch point with the current information in the <code>ongoingTouches</code> array.</p> + +<h4 id="Handling_the_end_of_a_touch">Handling the end of a touch</h4> + +<p>When the user lifts a finger off the surface, a {{event("touchend")}} event is sent. We handle this by calling the <code>handleEnd()</code> function below. Its job is to draw the last line segment for each touch that ended and remove the touch point from the ongoing touch list.</p> + +<pre class="brush: js">function handleEnd(evt) { + evt.preventDefault(); + log("touchend"); + var el = document.getElementsByTagName("canvas")[0]; + var ctx = el.getContext("2d"); + var touches = evt.changedTouches; + + for (var i = 0; i < touches.length; i++) { + var color = colorForTouch(touches[i]); + var idx = ongoingTouchIndexById(touches[i].identifier); + + if (idx >= 0) { + ctx.lineWidth = 4; + ctx.fillStyle = color; + ctx.beginPath(); + ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY); + ctx.lineTo(touches[i].pageX, touches[i].pageY); + ctx.fillRect(touches[i].pageX - 4, touches[i].pageY - 4, 8, 8); // and a square at the end + ongoingTouches.splice(idx, 1); // remove it; we're done + } else { + console.log("can't figure out which touch to end"); + } + } +} +</pre> + +<p>This is very similar to the previous function; the only real differences are that we draw a small square to mark the end and that when we call <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice"><code>Array.splice()</code></a>, we simply remove the old entry from the ongoing touch list, without adding in the updated information. The result is that we stop tracking that touch point.</p> + +<h4 id="Handling_canceled_touches">Handling canceled touches</h4> + +<p>If the user's finger wanders into browser UI, or the touch otherwise needs to be canceled, the {{event("touchcancel")}} event is sent, and we call the <code>handleCancel()</code> function below.</p> + +<pre class="brush: js">function handleCancel(evt) { + evt.preventDefault(); + console.log("touchcancel."); + var touches = evt.changedTouches; + + for (var i = 0; i < touches.length; i++) { + var idx = ongoingTouchIndexById(touches[i].identifier); + ongoingTouches.splice(idx, 1); // remove it; we're done + } +} +</pre> + +<p>Since the idea is to immediately abort the touch, we simply remove it from the ongoing touch list without drawing a final line segment.</p> + +<h3 id="Convenience_functions">Convenience functions</h3> + +<p>This example uses two convenience functions that should be looked at briefly to help make the rest of the code more clear.</p> + +<h4 id="Selecting_a_color_for_each_touch">Selecting a color for each touch</h4> + +<p>In order to make each touch's drawing look different, the <code>colorForTouch()</code> function is used to pick a color based on the touch's unique identifier. This identifier is an opaque number, but we can at least rely on it differing between the currently-active touches.</p> + +<pre class="brush: js">function colorForTouch(touch) { + var r = touch.identifier % 16; + var g = Math.floor(touch.identifier / 3) % 16; + var b = Math.floor(touch.identifier / 7) % 16; + r = r.toString(16); // make it a hex digit + g = g.toString(16); // make it a hex digit + b = b.toString(16); // make it a hex digit + var color = "#" + r + g + b; + console.log("color for touch with identifier " + touch.identifier + " = " + color); + return color; +} +</pre> + +<p>The result from this function is a string that can be used when calling {{HTMLElement("canvas")}} functions to set drawing colors. For example, for a {{domxref("Touch.identifier")}} value of 10, the resulting string is "#aaa".</p> + +<h4 id="Copying_a_touch_object">Copying a touch object</h4> + +<p>Some browsers (mobile Safari, for one) re-use touch objects between events, so it's best to copy the bits you care about, rather than referencing the entire object.</p> + +<pre class="brush: js">function copyTouch(touch) { + return { identifier: touch.identifier, pageX: touch.pageX, pageY: touch.pageY }; +}</pre> + +<h4 id="Finding_an_ongoing_touch">Finding an ongoing touch</h4> + +<p>The <code>ongoingTouchIndexById()</code> function below scans through the <code>ongoingTouches</code> array to find the touch matching the given identifier, then returns that touch's index into the array.</p> + +<pre class="brush: js">function ongoingTouchIndexById(idToFind) { + for (var i = 0; i < ongoingTouches.length; i++) { + var id = ongoingTouches[i].identifier; + + if (id == idToFind) { + return i; + } + } + return -1; // not found +} +</pre> + +<h4 id="Showing_what's_going_on">Showing what's going on</h4> + +<pre class="brush: js">function log(msg) { + var p = document.getElementById('log'); + p.innerHTML = msg + "\n" + p.innerHTML; +}</pre> + +<p>If your browser supports it, you can {{LiveSampleLink('Example', 'see it live')}}.</p> + +<p><a href="http://jsfiddle.net/Darbicus/z3Xdx/10/">jsFiddle example</a></p> + +<h2 id="Additional_tips">Additional tips</h2> + +<p>This section provides additional tips on how to handle touch events in your web application.</p> + +<h3 id="Handling_clicks">Handling clicks</h3> + +<p>Since calling <code>preventDefault()</code> on a {{event("touchstart")}} or the first {{event("touchmove")}} event of a series prevents the corresponding mouse events from firing, it's common to call <code>preventDefault()</code> on {{event("touchmove")}} rather than {{event("touchstart")}}. That way, mouse events can still fire and things like links will continue to work. Alternatively, some frameworks have taken to refiring touch events as mouse events for this same purpose. (This example is oversimplified and may result in strange behavior. It is only intended as a guide.)</p> + +<pre class="brush: js">function onTouch(evt) { + evt.preventDefault(); + if (evt.touches.length > 1 || (evt.type == "touchend" && evt.touches.length > 0)) + return; + + var newEvt = document.createEvent("MouseEvents"); + var type = null; + var touch = null; + + switch (evt.type) { + case "touchstart": + type = "mousedown"; + touch = evt.changedTouches[0]; + break; + case "touchmove": + type = "mousemove"; + touch = evt.changedTouches[0]; + break; + case "touchend": + type = "mouseup"; + touch = evt.changedTouches[0]; + break; + } + + newEvt.initMouseEvent(type, true, true, evt.originalTarget.ownerDocument.defaultView, 0, + touch.screenX, touch.screenY, touch.clientX, touch.clientY, + evt.ctrlKey, evt.altKey, evt.shiftKey, evt.metaKey, 0, null); + evt.originalTarget.dispatchEvent(newEvt); +} +</pre> + +<h3 id="Calling_preventDefault()_only_on_a_second_touch">Calling preventDefault() only on a second touch</h3> + +<p>One technique for preventing things like <code>pinchZoom</code> on a page is to call <code>preventDefault()</code> on the second touch in a series. This behavior is not well defined in the touch events spec, and results in different behavior for different browsers (i.e., iOS will prevent zooming but still allow panning with both fingers; Android will allow zooming but not panning; Opera and Firefox currently prevent all panning and zooming.) Currently, it's not recommended to depend on any particular behavior in this case, but rather to depend on meta viewport to prevent zooming.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Touch Events 2', '#touch-interface', 'Touch')}}</td> + <td>{{Spec2('Touch Events 2')}}</td> + <td>Added <code>radiusX</code>, <code>radiusY</code>, <code>rotationAngle</code>, <code>force</code> properties</td> + </tr> + <tr> + <td>{{SpecName('Touch Events', '#touch-interface', 'Touch')}}</td> + <td>{{Spec2('Touch Events')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<h3 id="Touch"><code>Touch</code></h3> + + + +<p>{{Compat("api.Touch")}}</p> + +<h3 id="Firefox_touch_events_and_multiprocess_(e10s)">Firefox, touch events, and multiprocess (e10s)</h3> + +<p>In Firefox, touch events are disabled when e10s (electrolysis; <a href="/en-US/docs/Mozilla/Firefox/Multiprocess_Firefox">multiprocess Firefox</a>) is disabled. e10s is on by default in Firefox, but can end up becoming disabled in certain situations, for example when certain accessibility tools or Firefox add-ons are installed that require e10s to be disabled to work. This means that even on a touchscreen-enabled desktop/laptop, touch events won't be enabled.</p> + +<p>You can test whether e10s is disabled by going to <code>about:support</code> and looking at the "Multiprocess Windows" entry in the "Application Basics" section. 1/1 means it is enabled, 0/1 means disabled.</p> + +<p>If you want to force e10s to be on — to explicitly re-enable touch events support — you need to go to <code>about:config</code> and create a new Boolean preference <code>browser.tabs.remote.force-enable</code>. Set it to <code>true</code>, restart the browser, and e10s will be enabled regardless of any other settings.</p> |