您的位置:首页 > Web前端 > HTML

html获取鼠标在页面的坐标以及在canvas上的坐标

2015-05-27 15:40 381 查看
以下程序实现了在canvas上画红色的圆,圆心为鼠标所在位置,其中圆的位置随着鼠标位置的移动而移动,js代码中mousePos(e)方法用于获取鼠标在整个页面的坐标,getCanvasPos(canvas,e)方法用于获取鼠标在canvas上的坐标;canvas以其左上角为起点,并设为(0,0),因此当页面包含其他元素的时候,两者坐标不一致,不过在本例中两者坐标是一致的,因为页面只包含一个canvas元素:

html代码如下:

<html>
<head></head>
<body>
<div onmousemove="draw(event)" id="testcanvas">
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;" >
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript" src="abc.js">
</script>
</div>
</body>
</html>
其中abc.js文件中的代码如下:

function mousePos(e)
{//获取鼠标所在位置的坐标,相对于整个页面
var x,y;
var e = e||window.event;
return {
x:e.clientX+document.body.scrollLeft + document.documentElement.scrollLeft,
y:e.clientY+document.body.scrollTop + document.documentElement.scrollTop
};
}

function getCanvasPos(canvas,e)
{//获取鼠标在canvas上的坐标
var rect = canvas.getBoundingClientRect();
return {
x: e.clientX - rect.left * (canvas.width / rect.width),
y: e.clientY - rect.top * (canvas.height / rect.height)
};
}
function draw(e)
{
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
cxt.clearRect(0,0,c.width,c.height);
cxt.fillStyle="#FF0000";
cxt.beginPath();
//cxt.arc(mousePos(e).x,mousePos(e).y,15,0,Math.PI*2,true);
cxt.arc(getCanvasPos(c,e).x,getCanvasPos(c,e).y,15,0,Math.PI*2,true);
cxt.closePath();
cxt.fill();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: