请用js写一段程序实现鼠标在网页上做框选操作时划出对应的矩形,边框用蓝色,填充用淡蓝的半透明色
时间: 2024-03-02 20:53:45 浏览: 39
好的,以下是实现代码:
```js
// 创建画布
let canvas = document.createElement("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
// 获取画布上下文
let ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(135, 206, 250, 0.3)";
ctx.strokeStyle = "#87CEFA";
// 定义变量
let isDragging = false;
let startX = 0;
let startY = 0;
let endX = 0;
let endY = 0;
// 添加事件监听器
canvas.addEventListener("mousedown", function(event) {
// 鼠标按下时记录起始坐标
startX = event.clientX;
startY = event.clientY;
isDragging = true;
});
canvas.addEventListener("mousemove", function(event) {
if (isDragging) {
// 鼠标移动时更新结束坐标,重绘矩形
endX = event.clientX;
endY = event.clientY;
redraw();
}
});
canvas.addEventListener("mouseup", function(event) {
// 鼠标松开时结束框选操作
isDragging = false;
});
// 重绘矩形
function redraw() {
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制矩形
let width = endX - startX;
let height = endY - startY;
ctx.fillRect(startX, startY, width, height);
ctx.strokeRect(startX, startY, width, height);
}
```
使用方法:将以上代码保存为 js 文件,在 HTML 页面中引入即可。当用户在页面上进行鼠标框选操作时,会在画布上绘制对应的矩形。
阅读全文