获取鼠标在HTML5 Canvas中的坐标

<!DOCTYPEHTML>

<html>

<head>

<style>

body{

margin:0px;

padding:0px;

}

</style>

</head>

<body>

<canvasid="myCanvas"width="578"height="200"></canvas>

<script>

functionwriteMessage(canvas,message){

varcontext=canvas.getContext('2d');

context.clearRect(0,0,canvas.width,canvas.height);

context.font='18ptCalibri';

context.fillStyle='black';

context.fillText(message,10,25);

}

functiongetMousePos(canvas,evt){

varrect=canvas.getBoundingClientRect();

return{

x:evt.clientX-rect.left,

y:evt.clientY-rect.top

};

}

varcanvas=document.getElementById('myCanvas');

varcontext=canvas.getContext('2d');

canvas.addEventListener('mousemove',function(evt){

varmousePos=getMousePos(canvas,evt);

varmessage='Mouseposition:'+mousePos.x+','+mousePos.y;

writeMessage(canvas,message);

},false);

</script>

</body>

</html>

相关推荐