fabric.js 实现框选效果
需求
实现在背景图上框选,并且返回当前框选的范围。
实现效果
技术选型
因为现有的项目已经引进了 fabric.js,所以决定使用该框架来实现。
准备工作
- 下载 fabric.js
- [fabric.js 入门](每一个用到canvas的小伙伴都应该了解的fabric.js - 掘金 (juejin.cn))
实现
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<title>fabric demo</title>
</head>
<body>
<script src="./fabric.js"></script>
<canvas id="canvas" width="1200" height="600"></canvas>
<script src="./main.js"></script>
</body>
</html>
style.css
* {
margin: 0;
padding: 0;
}
html, body {
width: 100vw;
height: 100vh;
}
body {
display: flex;
justify-content: center;
align-items: center;
}
js部分
var selectionRectConfig = {
width: 0,
height: 0,
left: 0,
top: 0,
fill: 'rgba(0, 0, 0, 0)',
selectable: false,
stroke: 'red',
strokeWidth: 2,
hoverCursor: 'default',
}
var selectionRect;
// hasClicked 用于标志当前用户按下鼠标准备框选
var hasClicked = true;
// 标志用户正按住鼠标左键拖拉框选
var isSelecting = false;
var canvas = new fabric.Canvas('canvas', {
selectionColor: 'rgba(255,212,173, 0.2)',
selectionLineWidth: 2,
backgroundImage: './cell.jpg',
});
canvas.setDimensions({
width: 1000,
height: 700,
});
canvas.on('mouse:down', function({ e }) {
hasClicked = true;
selectionRectConfig.left = e.offsetX;
selectionRectConfig.top = e.offsetY;
})
canvas.on('mouse:move', function() {
if(hasClicked) {
isSelecting = true;
canvas.set('selectionBorderColor', 'green');
}
})
canvas.on('mouse:up', function({ e }) {
if(isSelecting) {
// 清除之前的选中框
canvas.remove(selectionRect);
selectionRectConfig.width = e.offsetX - selectionRectConfig.left;
selectionRectConfig.height = e.offsetY - selectionRectConfig.top;
// 此时选中框的左上坐标以及宽度和高度
console.log(`选中框 X 轴的范围:${selectionRectConfig.left} ~ ${selectionRectConfig.left + selectionRectConfig.width}`
+ `\n选中框 Y 轴的范围:${selectionRectConfig.top} ~ ${selectionRectConfig.top + selectionRectConfig.height}`);
selectionRect = new fabric.Rect(selectionRectConfig);
canvas.add(selectionRect);
isSelecting = false;
hasClicked = false;
}