如何在 HTML5 canvas 上使用多個點選事件?


當在 canvas 上繪製一個圓時,我們在半圓區域填充紅色,在另一部分填充灰色,然後單擊紅色區域時,我們呼叫 function1。

單擊灰色部分時,呼叫 function 2,我們需要使用可重用的路徑物件來儲存不同部分,以便進行測試。單擊處理程式可用於共享 canvas 並進行所需操作。Path2D 物件可用於儲存路徑資訊。

var path1 = new Path2D();
var path2 = new Path2D();

var newpaths = [path1,path 2];   // Array is needed to store paths

path1.arc(200, 85,650, -0.2 * Math.PI, 2.7 * Math.PI);  // Path for red part
path2.arc(200, 85, 60, 2.7 * Math.PI, -1.1 * Math.PI);  //Path for  grey part


// Two path objects are rendered  using a common context ctx1, but with different style
ctx1.lineWidth = 16;
ctx1.strokeStyle = "#d43030";
ctx1.stroke(path1);
ctx1.strokeStyle = "#b8b8b8";
ctx1.stroke(path2);

然後使用 x 和 y 軸檢查 canvas 上的單擊操作。
然後遍歷路徑陣列,逐個測試路徑的點選情況。

<canvas id = "myCanvas1"></canvas> // Then it is attached with corresponding canvas.

更新於: 04-Mar-2020

334 次瀏覽

發揮你的 職業生涯

完成本課程取得資格認證

立即開始
廣告
© . All rights reserved.