1. 首页
  2. SEO技术

HTML5 Canvas获取鼠标位置坐标

gooood个人博客网站

canvas

为了获得相对于HTML5 Canvas的鼠标坐标,我们可以创建一个getMousePos()方法,该方法根据客户端鼠标的位置和从窗口对象的getBoundingClientRect()方法获得的画布的位置返回鼠标坐标。
说明:鼠标悬停在画布上以查看鼠标坐标
html代码:
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> <canvas></canvas> <script> function writeMessage(canvas, message) { var context = canvas.getContext('2d'); context.clearRect(0, 0, canvas.width, canvas.height); context.font = '18pt Calibri'; context.fillStyle = 'black'; context.fillText(message, 10, 25); } function getMousePos(canvas, evt) { var rect = canvas.getBoundingClientRect(); return { x: evt.clientX - rect.left, y: evt.clientY - rect.top }; } var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); canvas.addEventListener('mousemove', function(evt) { var mousePos = getMousePos(canvas, evt); var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y; writeMessage(canvas, message); }, false); </script> </body> </html>

本文来自SEO排名优化_SEO技术_SEO资讯网,经授权后发布,转载请联系原作者。原文链接:http://www.ylzug.com/js/478.html