您可以使用以下数学测试循环“声明”是否在点击“搜索半径”内:
var dx=mouseX-claimX;
var dy=mouseY-claimY;
if(dx*dx+dy*dy < searchRadius*searchRadius – claimRadius*claimRadius){
console.log(“This claim is within the search radius”);
}
这是如何使用此数学来揭示用户搜索范围内的声明的一个示例
左侧画布是用户进行搜索并仅显示搜索范围内的那些声明。
右侧的画布显示了所有声明。
这是代码和小提琴:http: //jsfiddle.net/m1erickson/4MY6z/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: black; padding:20px; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var reveal=document.getElementById("reveal");
var revealCtx=reveal.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var startX;
var startY;
var isDown=false;
var claims=[];
var searchRadius=50;
var searchRadius2=searchRadius*searchRadius;
for(var i=0;i<20;i++){
var x=parseInt(Math.random()*350);
var y=parseInt(Math.random()*250);
var radius=parseInt(Math.random()*10+10);
var color=randomColor();
claims.push({
x:x,
y:y,
radius:radius,
color:color
});
revealCtx.beginPath();
revealCtx.arc(x,y,radius,0,Math.PI*2,false);
revealCtx.fillStyle=color;
revealCtx.fill();
revealCtx.stroke();
}
// create a random color object {red,green,blue}
function randomColor(){
return("#"+Math.floor(Math.random()*16777215).toString(16));
}
function handleMouseMove(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
ctx.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<claims.length;i++){
var claim=claims[i];
var dx=mouseX-claim.x;
var dy=mouseY-claim.y;
var rr=claim.radius*claim.radius;
if(dx*dx+dy*dy<searchRadius2-rr){
ctx.beginPath();
ctx.arc(claim.x,claim.y,claim.radius,0,Math.PI*2,false);
ctx.closePath();
ctx.fillStyle=claim.color;
ctx.fill();
ctx.stroke();
}
}
// draw sighting scope
ctx.beginPath();
ctx.arc(mouseX,mouseY,searchRadius,Math.PI*2,false);
ctx.closePath();
ctx.moveTo(mouseX-searchRadius,mouseY);
ctx.lineTo(mouseX+searchRadius,mouseY);
ctx.moveTo(mouseX,mouseY-searchRadius);
ctx.lineTo(mouseX,mouseY+searchRadius);
ctx.fillStyle="white";
ctx.globalAlpha=.40;
ctx.fill();
ctx.stroke();
ctx.globalAlpha=1.00;
}
$("#canvas").mousemove(function(e){handleMouseMove(e);});
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=350 height=250></canvas>
<canvas id="reveal" width=350 height=250></canvas>
</body>
</html>