之前曾以iPad為對象寫過 為網頁加入多點觸控功能範例,如今支援觸控的Windows 8筆電在手,不改寫成IE10版怎能止癢?
經過 簡單研究,大致整理IE10與Safari/Chrome觸控事件差異如下:
把握以上重點,經過簡單修改,支援IE10的多點觸控展示網頁就完成囉~ 線上展示
Mutli-Touch Test
content="width=device-width, initial-scale=1.0, user-scalable=no">html,body {/* 停用預設的縮放、移動瀏覽(Panning)等觸控功能, 由自訂程式接管 */-ms-touch-action: none;}//http://msdn.microsoft.com/en-us/library/ie/hh673557(v=vs.85).aspx$.extend($.support, { ieTouch: "msMaxTouchPoints" in window.navigator });$(function () {//檢查是否為支援觸控功能的IE瀏覽器if (!$.support.ieTouch) {$("body").html("IE on touchable device only!");
return;}//使用canvas繪製回應var canvas = document.getElementById("sketchpad");var ctx = canvas.getContext("2d");//宣告變數儲存活動中觸控點的資訊var touches = {}, changedTouches = {};//傳回仿touchStart事件的touch物件function createTouchObject(e) {return { identifier: e.pointerId, pageX: e.clientX, pageY: e.clientY };}canvas.addEventListener("MSPointerDown", function (e) {//由於滑鼠也會觸發,先檢查pointerType,只針對觸控做反應if (e.pointerType != e.MSPOINTER_TYPE_TOUCH) return;var t = createTouchObject(e);touches[t.identifier] = t;});canvas.addEventListener("MSPointerMove", function (e) {if (e.pointerType != e.MSPOINTER_TYPE_TOUCH) return;var t = createTouchObject(e);var origT = touches[t.identifier];touches[t.identifier] = t;//與前次保存資料比較,偵測點觸控點是否移動if (origT &&Math.abs(t.pageX - origT.pageX) + Math.abs(t.pageY - origT.pageY) > 1)changedTouches[t.identifier] = t;elsedelete changedTouches[t.identifier];});canvas.addEventListener("MSPointerUp", function (e) {if (e.pointerType != e.MSPOINTER_TYPE_TOUCH) return;var t = createTouchObject(e);//停止活動,將觸控點自touches及changedTouches移除delete touches[t.identifier];delete changedTouches[t.identifier];});//定義不同顏色用來追蹤多點var colors =("red,orange,yellow,green,blue,indigo,purple," +"aqua,khaki,darkred,lawngreen,salmon,navy," +"deeppink,brown,olive,violet,tomato,gray").split(',');//在canvas繪製追蹤點ctx.lineWidth = 3;ctx.font = "10pt Arial";var r = 40;function drawPoint(i, x, y, c, id, chg) {ctx.beginPath();ctx.fillStyle = c;//若屬changedTouches則顯示黑框ctx.strokeStyle = chg ? "#000" : c;ctx.arc(x, y, r, 0, 2 * Math.PI, true);ctx.fill();ctx.stroke();//顯示touch的identifier及其在陣列中的序號//touches在上排藍字,chagedTouches在下排紅字ctx.fillStyle = chg ? "red" : "blue";ctx.fillText(id,x - r, y - r - 25 + (chg ? 15 : 0));}//清除canvasfunction clearCanvas() {ctx.clearRect(0, 0, canvas.width, canvas.height);}//利用identifier識別,相同時要保持同一個顏色var touchHash = {}, colorIdx = 0;function getColor(id) {if (touchHash[id] == undefined)touchHash[id] = ++colorIdx % colors.length;return colors[touchHash[id]];}//每秒更新20次,顯示目前的多點觸控資訊setInterval(function () {clearCanvas();//console.log(JSON.stringify(touches));for (var i in touches) {var t = touches[i];drawPoint(i, t.pageX, t.pageY, getColor(t.identifier),t.identifier);}for (var i in changedTouches) {var t = changedTouches[i];drawPoint(i, t.pageX, t.pageY, getColor(t.identifier),t.identifier, true);}}, 50);});
實測結果如下: (幸好最多只有10點,不然連腳都要舉起來"觸控"才能完成測試,肯定抽筋)