- 问题:在 fabric 画布中,判断图形是否在一矩形中。
1、准备结构和基本图形
<div class="box">
<canvas id="c" style="border: 1px solid pink;"></canvas>
</div>
const canvas = this.canvas = new fabric.Canvas('c', {
width: '800', // 画布宽度
height: '600', // 画布高度
backgroundColor: '#eee' // 画布背景色
})
// 矩形
const rect = new fabric.Rect({
top: 100, // 距离容器顶部 100px
left: 100, // 距离容器左侧 100px
fill: 'orange', // 填充 橙色
width: 50, // 宽度 50px
height: 50, // 高度 50px
stroke: 'orange', // 边框颜色:橙色
strokeWidth: 1, // 边框粗细:1px
lockScalingFlip: true, //锁定翻转,不可以拉到边的负值
})
// 准备一背景矩形
const back = new fabric.Rect({
top: (canvas.height - 300) / 2, // 距离容器顶部 居中,
left: (canvas.width - 400) / 2, // 距离容器左侧 居中
fill: 'pink', // 填充 橙色
width: 400, // 宽度 400px
height: 300, // 高度 300px
lockScalingFlip: true, //锁定翻转,及可不可以拉到边的负值
selectable:false,
})
canvas.add(rect, back) // 添加
back.moveTo(1) // 调整分层
rect.moveTo(2)
// 将矩形添加到画布中
canvas.renderAll() // 重绘
let flag = false
// 监听画布中的移动事件
canvas.on('mouse:move', (e) => {
if (!flag) return
let temp = this.judgement(rect, back)
console.log('hello world', temp);
})
rect.on(
'mousedown', (e) => { flag = true }
)
rect.on(
'mouseup', (e) => { flag = false }
)
2、主要函数
// 判断元素是否在某一矩形里面
judgement(group, back) {
if (!back || !group) {
return false
}
// tl,tr,bl,br
let top_left_x = group.aCoords.tl.x;
let top_left_y = group.aCoords.tl.y;
let top_right_x = group.aCoords.tr.x;
let top_right_y = group.aCoords.tr.y;
let bottom_left_x = group.aCoords.bl.x;
let bottom_left_y = group.aCoords.bl.y;
let bottom_right_x = group.aCoords.br.x;
let bottom_right_y = group.aCoords.br.y;
let backL = back.left;
let backT = back.top;
let backHeight = back.height * back.scaleY;
let backWidth = back.width * back.scaleX;
if (top_left_y < backT || top_right_y < backT || bottom_left_y < backT || bottom_right_y < backT ||
top_left_x < backL || top_right_x < backL || bottom_left_x < backL || bottom_right_x < backL ||
top_left_y > backHeight + backT || top_right_y > backHeight + backT || bottom_left_y > backHeight + backT || bottom_right_y > backHeight + backT ||
top_left_x > backL + backWidth || top_right_x > backL + backWidth || bottom_left_x > backL + backWidth || bottom_right_x > backL + backWidth) {
return false
} else {
return true;
}
},
主要思路:
- 获取图形的四个顶角坐标(相对于画布原点)
- 获取矩形 back 的上下边距离X轴值,获取矩形 back 的左右边距离Y轴值
- 判断 rect 四个顶点与 back 边的相对关系,进而做判断
- 例如:rect 四个顶点的x坐标都要大于 back 左边值,且小于右边值。Y轴比较也是同理
参考来源
https://blog.csdn.net/noscallion/article/details/120716616