Coordinates From Mouseclick Comparison
Solution 1:
A few gotchas with your existing code:
Notice that your “circle” is stretched vertically. That’s because the default size of a canvas is 300px wide and 150px high. When you use CSS to size it to 400x400 the canvas stretches disproportionally. To avoid this, either set your canvas size in the canvas tag or in javascript rather than in CSS.
// in html
<canvas id="canvas" width="400px" height="400px"></canvas>
// in javascript (do this before any drawing)
var canvas=document.getElementById(“canvas”);
canvas.width=400;
canvas.height=400;
Since you are hit-testing a circle that was generated in canvas coordinates (rather than window coordinates), you must get the position of your mouseclick in canvas coordinates too. This is a 2 step process.
First, get the position of the canvas relative to the window
var canvas=document.getElementById("canvas");
var offsetX=canvas.offsetLeft;
var offsetY=canvas.offsetTop;
Second, when handling mouseclicks you can get the canvas-relative mouse position like this:
var evt = e ? e:window.event;
clickX = evt.clientX-offsetX;
clickY = evt.clientY-offsetY;
Here is a better version of your hit-test. This uses the Pythagorean theorm to see if the mouseclick is within the radius of the circle:
var dx=cx-clickX;
var dy=cy-clickY;
if( dx*dx+dy*dy <= r*r )
{
alert("you are inside the circle");
}
(Optionally) here is how to use javascript to listen for click events in the canvas:
canvas.addEventListener("click",handleEvent);
(Optionally) You might take a look at jQuery which is a solid, excellent library that handles cross-browser differences so you don't have to do this:
var evt = e ? e:window.event;
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/zLzwU/
<!doctype html>
<html>
<head>
<link 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: #3e3e3e;
}
#canvas{
background:white;
border: 2px solid yellow;
}
</style>
<script>
window.onload=function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var offsetX=canvas.offsetLeft;
var offsetY=canvas.offsetTop;
var cx=canvas.width/2;
var cy=canvas.height/2;
var r=20;
ctx.beginPath();
ctx.arc(cx,cy,r,0,2*Math.PI,false);
ctx.closePath();
ctx.stroke();
function handleEvent(e){
var evt = e ? e:window.event;
clickX = evt.clientX-offsetX;
clickY = evt.clientY-offsetY;
var dx=cx-clickX;
var dy=cy-clickY;
if( dx*dx+dy*dy <= r*r )
{
alert("you are inside the circle");
}
return false;
}
canvas.addEventListener("click",handleEvent);
}; // end init;
</script>
</head>
<body>
<canvas id="canvas" width="400px" height="400px"></canvas>
</body>
</html>
Post a Comment for "Coordinates From Mouseclick Comparison"