如何在 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.