-
Notifications
You must be signed in to change notification settings - Fork 0
/
canvas定位鼠标光标位置.html
43 lines (41 loc) · 1.31 KB
/
canvas定位鼠标光标位置.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html>
<html>
<head>
<title>相对于canvas坐标 | html5笔记</title>
<link rel="icon" href="./favicon.ico" type="image/x-icon">
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" style="display: block;margin: 20px auto;background:gray" width="578" height="200"></canvas>
<script>
//canvas上输出,鼠标光标 相对于 canvas左上角 的位置
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();
console.log(rect);
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>