判断点击点是否在圆环(圆)内
Posted 离丶花香
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了判断点击点是否在圆环(圆)内相关的知识,希望对你有一定的参考价值。
这是移动端判断事件touch,pc端一样的。
首先先画出来一个圆环;
下面是html代码
<div class="circleHandle"> <div class="cirAround"> <div class="cirAro"></div> <div class="point pointtop"></div> <div class="point pointright"></div> <div class="point pointbtm"></div> <div class="point pointleft"></div> <div class="cirAffrim">ok</div> </div> </div>
然后是css
.circleHandle{ display: flex; align-items: center; justify-content: center; } .cirAround{ width: 160px; height: 160px; border:40px solid transparent; border-radius: 50%; position: relative; z-index: 100; } .point{ width: 8px; height: 8px; background: #575757; border-radius: 50%; position:absolute; } .pointtop{ top: -24px; left: 36px; } .pointright{ top: 36px; right: -24px; } .pointbtm{ bottom: -24px; left: 36px } .pointleft{ top: 36px; left: -24px; } .cirAro{ position: absolute; top: -40px; left: -40px; width: 160px; height: 160px; border: 1px solid #9DA0A5; border-radius: 50%; z-index: 1; } .cirAffrim{ position: absolute; border:1px solid #9DA0A5; width:100%; height: 100%; background-color: #F1F5F6; border-radius: 50%; line-height:78px; text-align: center; font-size:16px; font-family: "黑体"; z-index: 200; }
接下来是js
//获取点击点位所在父元素坐标 var getElPosition = function(el){ var t = el.offsetTop, l = el.offsetLeft; while( el = el.offsetParent){ t += el.offsetTop; l += el.offsetLeft; } return { x : parseInt(l), y : parseInt(t) }; }; $(".cirAround").on("touchstart",function(e){ e.stopPropagation(); var w=parseInt($(".cirAround").css("border-width")); var a={x:0,y:0},b={x:0,y:0},c={x:0,y:0}//a为圆心,b为上面点,c为点击点,d为左边点 a.x=getElPosition(this).x+w*2; a.y=getElPosition(this).y+w*2; b.x=getElPosition(this).x+w*2; b.y=getElPosition(this).y+w/2; c.x=parseInt(e.changedTouches[0].clientX); c.y=parseInt(e.changedTouches[0].clientY); var angel=getAngel(a,b,c); //当angel大于0.5时为上面,小于-0.5时在下面 if(angel>0.5){ $(".cirAround").css("border-color","transparent"); $(".cirAround").css("border-top-color","#C8CACD"); }else if(angel<-0.5){ $(".cirAround").css("border-color","transparent"); $(".cirAround").css("border-bottom-color","#C8CACD"); }else{ //x坐标小于圆心坐标为左边的,大于的话为右边 if(c.x<a.x){ $(".cirAround").css("border-color","transparent"); $(".cirAround").css("border-left-color","#C8CACD"); }else{ $(".cirAround").css("border-color","transparent"); $(".cirAround").css("border-right-color","#C8CACD"); } } }) $(".cirAround").on("touchend",function(e){ $(".cirAround").css("border-color","transparent"); }) //计算cos值,数学中两个向量计算夹角的方法 function getAngel(a,b,c){ var ac={x:0,y:0,abs:0},ab={x:0,y:0,abs:0}; ac.x=c.x-a.x; ac.y=c.y-a.y; ab.x=b.x-a.x; ab.y=b.y-a.y; ac.abs=Math.sqrt(ac.x*ac.x+ac.y*ac.y); ab.abs=Math.sqrt(ab.x*ab.x+ab.y*ab.y); var angel=(ac.x*ab.x+ac.y*ab.y)/(ac.abs*ab.abs) return angel; }
这样就实现了点击时判断在哪个圆环中,如下图
自己学的数学已经全部还给美术老师了···(╯▽╰)
以上是关于判断点击点是否在圆环(圆)内的主要内容,如果未能解决你的问题,请参考以下文章
POJ 1584 A Round Peg in a Ground Hole(凸多边形判断 + 点是否在多边形内 + 点到线段的最短距离)