html获取鼠标在页面的坐标以及在canvas上的坐标
2015-05-27 15:40
381 查看
以下程序实现了在canvas上画红色的圆,圆心为鼠标所在位置,其中圆的位置随着鼠标位置的移动而移动,js代码中mousePos(e)方法用于获取鼠标在整个页面的坐标,getCanvasPos(canvas,e)方法用于获取鼠标在canvas上的坐标;canvas以其左上角为起点,并设为(0,0),因此当页面包含其他元素的时候,两者坐标不一致,不过在本例中两者坐标是一致的,因为页面只包含一个canvas元素:
html代码如下:
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(); }
相关文章推荐
- QCustomPlot 鼠标消息获取,以及对应坐标转换
- 关于swing中嵌入html页面以及获取绝对路径
- event获取页面鼠标点击位置坐标
- JS获取area元素坐标和鼠标在页面中的位置
- html5中canvas的使用 获取鼠标点击页面上某点的RGB
- 【实例】【html5】在canvas获取鼠标的坐标
- 获取整个页面HTML的信息以及注意事项
- JS获取最底层iframe页面中鼠标点击的坐标
- HTML页面上获取鼠标的位置(备忘)
- 在页面中js获取光标/鼠标的坐标及光标的像素坐标
- [js高手之路] html5 canvas动画教程 - 实时获取鼠标的当前坐标
- Unity中UGUI中获取鼠标点击位置以及UI物体的屏幕坐标
- 在页面中 js 获取光标/鼠标的坐标,获取光标的的像素坐标
- JS获取页面鼠标点击位置的坐标
- Java获取窗口鼠标坐标以及键盘
- 鼠标滑动显示不同页面的效果——————获取鼠标相对于整个页面的坐标
- 获取canvas中鼠标的坐标
- 从0开始html前端页面开发_CSS实现图像获取鼠标焦点逐渐变大动画效果
- HTML--js获取鼠标点击坐标
- 在页面中js获取光标/鼠标的坐标及光标的像素坐标