web 鼠标划线并保存坐标
时间: 2023-09-19 13:06:20 浏览: 118
获取与保存鼠标坐标
4星 · 用户满意度95%
要实现这个功能,你需要使用JavaScript来捕获鼠标移动事件并记录坐标。下面是一个简单的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Mouse Coordinates</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var isDrawing = false;
var startX, startY;
canvas.addEventListener('mousedown', function(e) {
isDrawing = true;
startX = e.clientX - canvas.offsetLeft;
startY = e.clientY - canvas.offsetTop;
});
canvas.addEventListener('mousemove', function(e) {
if (isDrawing) {
var x = e.clientX - canvas.offsetLeft;
var y = e.clientY - canvas.offsetTop;
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.lineTo(x, y);
ctx.stroke();
startX = x;
startY = y;
}
});
canvas.addEventListener('mouseup', function(e) {
isDrawing = false;
});
canvas.addEventListener('mouseleave', function(e) {
isDrawing = false;
});
function saveCoordinates() {
var coordinates = [];
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var pixels = imageData.data;
for (var y = 0; y < canvas.height; y++) {
for (var x = 0; x < canvas.width; x++) {
var index = (y * canvas.width + x) * 4;
if (pixels[index] != 0) {
coordinates.push({x: x, y: y});
}
}
}
console.log(coordinates);
}
</script>
</body>
</html>
```
在这个示例中,我们使用`canvas`元素来绘制鼠标移动时的轨迹,并通过`getImageData()`方法获取每个点的像素值。如果像素值不为0,则将该点的坐标添加到`coordinates`数组中。最后,我们可以使用`console.log()`将坐标打印到控制台。
你可以根据自己的需求修改代码并添加更多功能。
阅读全文