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"); }); </script> <template> diff --git a/src/views/deviceSetting/index.scss b/src/views/deviceSetting/index.scss index fb2499e..a6f29a0 100644 --- a/src/views/deviceSetting/index.scss +++ b/src/views/deviceSetting/index.scss @@ -65,7 +65,7 @@ } .point_detail_wrap { .deviceOfPoint_wrap { - background-color: red; + background-color: goldenrod; height: calc(100vh - 290px); } .footer_btns {