命中測試城市圈在畫布上
要檢查,如果用戶在你的城市圈的一個點擊,使用畢達哥拉斯相關的點擊測試:
var dx = cityCenterX – clickX;
var dy = cityCenterY – clickY;
var radius=cityRadius;
var IsInCity = (dx*dx+dy*dy)<(cityRadius*cityRadius);
這裏是代碼和一個小提琴:http://jsfiddle.net/m1erickson/Bgh9d/
<!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: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
// define some cities
var cities=[];
cities.push({x:100, y:75, radius:50, name:"large city"});
cities.push({x:200, y:100, radius:30, name:"medium city"});
cities.push({x:150, y:150, radius:25, name:"small city"});
// draw cities
ctx.beginPath();
ctx.lineWidth=3;
ctx.strokeStyle="blue";
for (var i=0;i<cities.length;i++){
ctx.beginPath();
ctx.arc(cities[i].x, cities[i].y, cities[i].radius, 0 , 2 * Math.PI, false);
ctx.stroke();
}
function handleMouseDown(e){
// get canvasXY of click
canvasMouseX=parseInt(e.clientX-offsetX);
canvasMouseY=parseInt(e.clientY-offsetY);
// test if we clicked in any cities
for(var i=0;i<cities.length;i++){
var dx=canvasMouseX-cities[i].x;
var dy=canvasMouseY-cities[i].y;
var isInCity=(dx*dx+dy*dy)<(cities[i].radius*cities[i].radius);
if(isInCity){
alert("You clicked in the "+cities[i].name);
}
}
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>