热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何使用HTML5画布找出点击圈子的哪个部分?-Howtofindoutwhichpartofthecirclewasclicked,usingHTML5canvas?

IamtryingtocreateSimongameusingHTML5canvasandvanillaJavaScript.Iamconfusedaboutthe

I am trying to create Simon game using HTML5 canvas and vanilla Javascript. I am confused about the coordinate system in the arc() method. I have divided the circle into 4 quadrants and would like to alert the number of the quadrant clicked. But, I am not sure how to find out which part of the circle was clicked. https://jsfiddle.net/xawpLdys/1/

我正在尝试使用HTML5 canvas和vanilla Javascript创建Simon游戏。我对arc()方法中的坐标系感到困惑。我已将圆圈划分为4个象限,并想提醒点击的象限数量。但是,我不知道如何找出圈子的哪个部分被点击。 https://jsfiddle.net/xawpLdys/1/

var canvas = document.getElementById('myCanvas');
var cOntext= canvas.getContext('2d');
var x = canvas.width / 2;
var y = canvas.height / 2;

var pads = [];

var angle = 2 * Math.PI / 4;
var color = ["green","red","blue","yellow"];
var Pads = function(x, y, radius, start, end) {
   this.x = x;
   this.y = y;
   this.radius = radius;
   this.start = start;
   this.end = end;

};
function drawSimon(radius) {
for (var i = 0; i <4; i++) {
    context.beginPath();
    context.moveTo(x, y);
    context.arc(x, y, radius, i*angle, (i+1)*angle, false);
    context.lineWidth = radius;
    context.fillStyle = color[i];
    context.fill();
    context.lineWidth = 2;
    context.strokeStyle = '#444';
    context.stroke();
    var pad = new Pads(x, y, radius, i*angle, (i+1)*angle);
    pads.push(pad);
}

}

 drawSimon(150);

  $('#myCanvas').click(function (e) {

  /*for (var i = 0; i 

2 个解决方案

#1


2  

Try This

This example just translates the clicked e.pageX and e.pageY to normal quadrant system. And after some condition, you can determine which part has been clicked.

此示例仅将单击的e.pageX和e.pageY转换为正常象限系统。在某些条件之后,您可以确定单击了哪个部分。

    $('#myCanvas').click(function (e) {
    var nx,ny;
    nx=-(x- e.pageX);
    ny=y- e.pageY;
        if (nx>0 && ny>0){
      alert('Yellow');
      }else if (nx<0 && ny>0){
      alert('Blue');
      }else if (nx>0 && ny<0){
      alert('Green');
      }else if (nx<0 && ny<0){
      alert('Red');
      }

    });

Here is the fiddle https://jsfiddle.net/xawpLdys/3/

这是小提琴https://jsfiddle.net/xawpLdys/3/

UPDATE

John S was right, (It counts clicks that are outside the circle). To prevent the clicks outside the circle from considering, we need to just find the distance from the center of the circle and the clicked point. Then compare the distance with the circle's radius to see it is inside radius.

John S是对的,(它会计算圈外的点击次数)。为了防止圆圈外的咔嗒声被考虑,我们需要找到距离圆心和点击点的距离。然后将距离与圆的半径进行比较,看它是否在半径范围内。

The updated code :

更新的代码:

    $('#myCanvas').click(function (e) {
    var nx,ny;
    nx=-(x- e.pageX);
    ny=y- e.pageY;
     var dx = Math.abs(Math.abs(x)-Math.abs(e.pageX));
     var dy = Math.abs(Math.abs(y)-Math.abs(e.pageY));
     var distance_clicked = Math.sqrt((dx*dx)+(dy*dy));
     if(distance_clicked <= radius){
        if (nx>0 && ny>0){
          alert('Yellow');
          }else if (nx<0 && ny>0){
          alert('Blue');
          }else if (nx>0 && ny<0){
          alert('Green');
          }else if (nx<0 && ny<0){
          alert('Red');
          }
    }
    });

Here is the updated fiddle https://jsfiddle.net/xawpLdys/8/

这是更新的小提琴https://jsfiddle.net/xawpLdys/8/

It still have the limitations of dividing the circle more than 4 slices.

它仍然具有将圆分割超过4个切片的限制。

#2


0  

The accepted answer seems a bit limited. It counts clicks that are outside the circle. That could be fixed fairly easily, but it would still be limited to four sections.

接受的答案似乎有点受限。它会计算圈子外的点击次数。这可以很容易地修复,但它仍然只限于四个部分。

To determine if a point is in a sector:

要确定某个点是否在某个扇区中:

  1. First check if it is within the circle. The Pythagorean theorem comes into play here. Square the x and y values, if their sum is less than or equal to the radius squared, the point is in the circle.
  2. 首先检查它是否在圆圈内。毕达哥拉斯定理在这里发挥作用。将x和y值平方,如果它们的总和小于或等于半径的平方,则该点在圆中。

  3. If the point is in the circle, then check if its angle is between the start and end angles for the sector. You can get the point's angle using the arc tangent function from trigonometry.
  4. 如果该点位于圆圈中,则检查其角度是否在扇区的起始角度和结束角度之间。您可以使用三角函数的反正切函数获得点的角度。


Try this jsfiddle.

试试这个jsfiddle。

Here are the types that help make this work:

以下是有助于实现此功能的类型:

var Circle = function(center, radius) {
    this.center = center;
    this.radius = radius;

    this._radiusSquared = Math.pow(this.radius, 2);
}

$.extend(Circle.prototype, {
    containsPoint: function(point) {
        var relPoint = this.pointToRelPoint(point);
        return Math.pow(relPoint.x, 2) + Math.pow(relPoint.y, 2)
                <= this._radiusSquared;
    },

    getAngleForPoint: function(point) {
        var relPoint = this.pointToRelPoint(point);
        return Math.atan2(-relPoint.y, -relPoint.x) + Math.PI;
    },

    pointToRelPoint: function(point) {
        return { x: point.x - this.center.x, y: point.y - this.center.y }
    }
});

var CircleSector = function(startAngle, endAngle) {
    this.startAngle = startAngle;
    this.endAngle = endAngle;
};

$.extend(CircleSector.prototype, {
    containsAngle: function(angle) {
        return (angle >= this.startAngle) && (angle 

推荐阅读
  • 本文介绍了一个在线急等问题解决方法,即如何统计数据库中某个字段下的所有数据,并将结果显示在文本框里。作者提到了自己是一个菜鸟,希望能够得到帮助。作者使用的是ACCESS数据库,并且给出了一个例子,希望得到的结果是560。作者还提到自己已经尝试了使用"select sum(字段2) from 表名"的语句,得到的结果是650,但不知道如何得到560。希望能够得到解决方案。 ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
  • This article discusses the efficiency of using char str[] and char *str and whether there is any reason to prefer one over the other. It explains the difference between the two and provides an example to illustrate their usage. ... [详细]
  • 带添加按钮的GridView,item的删除事件
    先上图片效果;gridView无数据时显示添加按钮,有数据时,第一格显示添加按钮,后面显示数据:布局文件:addr_manage.xml<?xmlve ... [详细]
  • 字符串匹配RabinKarp算法讲解
    问题描述:Rabin-Karp的预处理时间是O(m),匹配时间O((n-m1)m)既然与朴素算法的匹配时间一样,而且还多了一些预处理时间& ... [详细]
  • 2021年最详细的Android屏幕适配方案汇总
    1Android屏幕适配的度量单位和相关概念建议在阅读本文章之前,可以先阅读快乐李同学写的文章《Android屏幕适配的度量单位和相关概念》,这篇文章 ... [详细]
  • dp[i][j]+dp[i-1][k],match(j,k). 与其说是DP,不如说是模拟题。第一个和最后一个数字要单独讨论,中间的要符合剩下的条件:中间一列和剩下的两 ... [详细]
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • 生成式对抗网络模型综述摘要生成式对抗网络模型(GAN)是基于深度学习的一种强大的生成模型,可以应用于计算机视觉、自然语言处理、半监督学习等重要领域。生成式对抗网络 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • 本文介绍了使用Python编写购物程序的实现步骤和代码示例。程序启动后,用户需要输入工资,并打印商品列表。用户可以根据商品编号选择购买商品,程序会检测余额是否充足,如果充足则直接扣款,否则提醒用户。用户可以随时退出程序,在退出时打印已购买商品的数量和余额。附带了完整的代码示例。 ... [详细]
  • Android自定义控件绘图篇之Paint函数大汇总
    本文介绍了Android自定义控件绘图篇中的Paint函数大汇总,包括重置画笔、设置颜色、设置透明度、设置样式、设置宽度、设置抗锯齿等功能。通过学习这些函数,可以更好地掌握Paint的用法。 ... [详细]
  • 本文详细介绍了Android中的坐标系以及与View相关的方法。首先介绍了Android坐标系和视图坐标系的概念,并通过图示进行了解释。接着提到了View的大小可以超过手机屏幕,并且只有在手机屏幕内才能看到。最后,作者表示将在后续文章中继续探讨与View相关的内容。 ... [详细]
author-avatar
点提土八撇又254
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有