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


當我們在畫布上繪製了一個圓圈,並在一半上填入紅色,在圓圈的一部分上填入灰色後,再點選紅色時,我們呼叫了函式 1。

在點選灰色部分時,會呼叫函式 2,並且我們需要使用可重複使用的路徑物件來儲存不同的部分,以便進行測試。單擊處理程式可用於共享畫布並完成我們想要執行的工作。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 id = "myCanvas1"></canvas> // Then it is attached with corresponding canvas.

更新於:04-Mar-2020

331 次瀏覽

開啟你的職業生涯

完成課程並獲得認證

開始
廣告