标签:body cli move use 坐标 添加 load 返回 overflow
如何用JavaScript获取鼠标点击时在canvas画布上的坐标呢:
代码如下:
--------------------------------------------------------------
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>demo</title> 6 <style type="text/css"> 7 *{ 8 margin:0; 9 padding:0; 10 } 11 #canvas{ 12 background:green; 13 width:100%; 14 height:100%; 15 } 16 body,html{ 17 overflow:hidden; 18 width:100%; 19 height:100%; 20 } 21 </style> 22 <script type="text/javascript"> 23 window.onload = function(){ 24 25 var canvas = document.getElementById(‘canvas‘); //获取画布; 26 27 var utils = {}; //创建空对象; 28 canvas.style.height = document.body.clientHeight; //设置全屏高度; 29 utils.captureMouse = function(canvas){ //添加方法; 30 var mouse = {x:0,y:0}; //初始化坐标位置; 31 canvas.addEventListener(‘mousemove‘,function(event){ //添加点击监听事件 32 var x,y; 33 if(event.pageX || event.pageY){ 34 x = event.pageX; 35 y = event.pageY; 36 }else{ 37 x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; 38 y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop; 39 } 40 x -= canvas.offsetLeft; 41 y -= canvas.offsetTop; 42 43 mouse.x = x; //获取x轴坐标; 44 mouse.y = y; //获取Y轴坐标; 45 },false) 46 return mouse; //返回坐标; 47 }; 48 49 mouse = utils.captureMouse(canvas); //实例化对象,传入参数; 50 51 canvas.addEventListener(‘click‘,function(){ 52 alert("x: " + mouse.x + ", y: " + mouse.y); //弹出坐标; 53 },false); 54 }; 55 </script> 56 </head> 57 <body> 58 <canvas id="canvas"></canvas> //创建canvas画布; 59 </body> 60 </html>
-----------------------------------------------------------
上面就是获取canvas画布上的坐标值了,将它封装起来,
放到单独的js文件中,需要用的时候再引入进去,就是一
个很好的工具了
-----------------------------------------------------------
感谢你的阅读,请继续支持博主哦!!!
标签:body cli move use 坐标 添加 load 返回 overflow
原文地址:http://www.cnblogs.com/qmdx00/p/7425569.html