如何在 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 次浏览

开启你的职业生涯

完成课程并获得认证

开始
广告
© . All rights reserved.