From c0f96ae2a743d260f8d710216f15f560de69c952 Mon Sep 17 00:00:00 2001 From: JINGYJ <1458671527@qq.com> Date: Wed, 14 Aug 2024 15:58:42 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E9=99=90=E5=88=B6=E5=85=83=E7=B4=A0?= =?UTF-8?q?=E5=9C=A8=E7=94=BB=E5=B8=83=E5=86=85=E6=8B=96=E5=9C=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../deviceSetting/components/deviceAttr.vue | 44 +++++++++++++++++++ src/views/deviceSetting/index.scss | 2 +- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/views/deviceSetting/components/deviceAttr.vue b/src/views/deviceSetting/components/deviceAttr.vue index cba63be..32f385e 100644 --- a/src/views/deviceSetting/components/deviceAttr.vue +++ b/src/views/deviceSetting/components/deviceAttr.vue @@ -105,6 +105,41 @@ const fontAttr = reactive({ overline: false }); +// 获取画布边界 +const getCanvasBoundaries = () => { + const canvasObj = canvasEditor.canvas.getObjects()[1]; + return { + width: canvasObj.width, + height: canvasObj.height + }; +}; + +const constrainObjectWithinCanvas = obj => { + const { width, height } = getCanvasBoundaries(); + + // 获取对象的当前尺寸和位置 + const objLeft = obj.left; + const objTop = obj.top; + const objWidth = obj.width * obj.scaleX; + const objHeight = obj.height * obj.scaleY; + // 限制对象在画布内移动 + if (objLeft < 0) { + obj.left = 0; + } + if (objTop < 0) { + obj.top = 0; + } + if (objLeft + objWidth > width) { + obj.left = width - objWidth; + } + if (objTop + objHeight > height) { + obj.top = height - objHeight; + } + + // 更新对象的位置 + obj.setCoords(); +}; + const getObjectAttr = e => { const activeObject = canvasEditor.canvas.getActiveObject(); // 不是当前obj,跳过 @@ -159,6 +194,14 @@ const init = () => { event.on("selectCancel", selectCancel); event.on("selectOne", getObjectAttr); canvasEditor.canvas.on("object:modified", getObjectAttr); + // 监听 object:moving 事件以限制移动范围 + canvasEditor.canvas.on("object:moving", e => { + const activeObject = e.target; + if (activeObject) { + constrainObjectWithinCanvas(activeObject); + canvasEditor.canvas.renderAll(); + } + }); }; // 通用属性改变 @@ -260,6 +303,7 @@ onBeforeUnmount(() => { event.off("selectCancel", selectCancel); event.off("selectOne", getObjectAttr); canvasEditor.canvas.off("object:modified", getObjectAttr); + canvasEditor.canvas.off("object:moving"); });