代码链接 1.以下代码在 html5 画布上绘制一个圆圈,并添加一个事件监听器以获取鼠标点击。圈内的鼠标点击无法与圈外的点击区分开来。
<body>
<canvas id="canvas" onclick="handleEvent()"></canvas>
</body>
body{
background: #3e3e3e;
}
#canvas{
background:white;
height: 400px;
width: 400px;
border: 2px solid yellow;
}
window.onload=function(){
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext('2d');
var cx=canvas.width/2;
var cy=canvas.height/2;
var r=20;
//circle draw function
ctx.beginPath();
ctx.arc(cx,cy,r,0,2*Math.PI,false);
ctx.stroke();
}
//function to get mouse click coordinates
function handleEvent(e)
{
var evt = e ? e:window.event;
var clickX=0, clickY=0;
if (evt.pageX || evt.pageY)
{
clickX = evt.pageX;
clickY = evt.pageY;
}
if(180<evt.pageX<220)
{
alert("you are inside the circle");
}
alert (evt.type.toUpperCase() + ' mouse event:'
+'\n pageX = ' + clickX
+'\n pageY = ' + clickY
)
return false;
}