这是关于HTML5画布的问题。当鼠标在画布上时,我希望能够看到类似于x:11, y:33
的提示框,就像这样... 鼠标移动时,提示框也随之移动并显示坐标。如何使用JavaScript和HTML5实现这样的功能?
这是关于HTML5画布的问题。当鼠标在画布上时,我希望能够看到类似于x:11, y:33
的提示框,就像这样... 鼠标移动时,提示框也随之移动并显示坐标。如何使用JavaScript和HTML5实现这样的功能?
$(function() {
var canvas = $('#canvas').get(0);
var ctx = canvas.getContext('2d');
var w = h = canvas.width = canvas.height = 300;
ctx.fillStyle = '#0099f9';
ctx.fillRect(0, 0, w, h);
canvas.addEventListener('mousemove', function(e) {
var x = e.pageX - canvas.offsetLeft;
var y = e.pageY - canvas.offsetTop;
var str = 'X : ' + x + ', ' + 'Y : ' + y;
ctx.fillStyle = '#0099f9';
ctx.fillRect(0, 0, w, h);
ctx.fillStyle = '#ddd';
ctx.fillRect(x + 10, y + 10, 80, 25);
ctx.fillStyle = '#000';
ctx.font = 'bold 20px verdana';
ctx.fillText(str, x + 20, y + 30, 60);
}, 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas"></canvas>