随、风 2024-08-05 10:15 采纳率: 28.6%
浏览 13

vue3画矩形可拖拽移动,

vue3画矩形可拖拽移动,可拖拽更改尺寸大小,可填充矩形颜色,矩形内部写文字。保存坐标

  • 写回答

1条回答 默认 最新

  • Nymph_Zhu 2024-08-05 13:41
    关注

    父组件代码:

    <template>
      <Rectangle
        :initialX="300"
        :initialY="100"
        :initialWidth="200"
        :initialHeight="100"
        :initialColor="'red'"
        text="demo"
      />
    </template>
     
    <script>
    import Rectangle from './rectangle.vue';
     
    export default {
      components: {
        Rectangle
      }
    };
    </script>
    
    
    

    子组件代码:

    <template>
      <div
        class="rectangle"
        :style="style"
        @mousedown="initDrag"
      >
        <div class="content" v-if="text">{{ text }}</div>
      </div>
    </template>
     
    <script>
    import { reactive, computed } from 'vue';
     
    export default {
      props: {
        text: String,
        initialX: Number,
        initialY: Number,
        initialWidth: Number,
        initialHeight: Number,
        initialColor: String,
      },
      setup(props) {
        const state = reactive({
          isDragging: false,
          x: props.initialX,
          y: props.initialY,
          width: props.initialWidth,
          height: props.initialHeight,
          color: props.initialColor,
        });
     
        const saveState = () => {
          // 保存状态逻辑,例如使用localStorage
        };
     
        const style = computed(() => ({
          position: 'absolute',
          left: `${state.x}px`,
          top: `${state.y}px`,
          width: `${state.width}px`,
          height: `${state.height}px`,
          backgroundColor: state.color,
        }));
     
        const initDrag = (event) => {
          state.isDragging = true;
          const offsetX = event.clientX - state.x;
          const offsetY = event.clientY - state.y;
     
          const move = (event) => {
            if (state.isDragging) {
              state.x = event.clientX - offsetX;
              state.y = event.clientY - offsetY;
            }
          };
     
          const stopMove = () => {
            state.isDragging = false;
            document.removeEventListener('mousemove', move);
            document.removeEventListener('mouseup', stopMove);
            saveState();
          };
     
          document.addEventListener('mousemove', move);
          document.addEventListener('mouseup', stopMove);
        };
     
        return {
          state,
          style,
          initDrag,
        };
      },
    };
    </script>
     
    <style scoped>
    .rectangle {
      cursor: move;
      border: 1px solid black;
    }
    .content {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      text-align: center;
      user-select: none;
    }
    </style>
    
    
    
    评论

报告相同问题?

问题事件

  • 创建了问题 8月5日