在画布中如何实现组件选中、删除与层级调整

解读

国内前端面试常把“低代码/可视化搭建”作为高频深挖场景,本题聚焦画布交互三件套:选中、删除、层级调整。面试官想确认三点:

  1. 你是否理解“画布”本质是 React 组件树的可视化映射;
  2. 能否用纯 React 状态管理(或轻量状态库)完成增删改查,而不依赖第三方画布引擎;
  3. 对性能、可维护性、快捷键、撤销重做等工程细节是否有落地经验。
    回答时先给出数据结构设计,再讲交互流程,最后补性能与可扩展性,节奏控制在 3~5 分钟,代码量以“能讲清思路”为度。

知识点

  1. 受控组件思想:画布所有图形对应一份不可变 JSON(DSL),任何操作都返回新 DSL,React 仅做 diff 渲染。
  2. 双坐标系转换:屏幕事件坐标 → 画布逻辑坐标(考虑缩放、平移、滚动条)。
  3. 选中策略:
    • 点选:事件冒泡到画布,做矩形碰撞(box-model)或像素级判断(svg path)。
    • 框选:mousedown → mousemove → mouseup 绘制选区矩形,收集交集节点。
  4. 删除:不可变删除需保持引用稳定,避免子组件 key 抖动;同时把删除节点快照写入历史栈,供撤销。
  5. 层级调整:
    • 绝对层级:DSL 用数组顺序表示 z-index,调整即在数组内移动元素。
    • 相对层级:提供“置顶 / 置底 / 上移一层 / 下移一层”四种语义,时间复杂度 O(1) 或 O(n)。
  6. 事件委托:在画布根节点统一监听 mousedown、keydown,避免给每个图形绑监听器。
  7. Hooks 组合:
    • useCanvas:返回画布 DSL、dispatch、undo、redo。
    • useSelection:维护 selectedIds,提供单选、多选、框选逻辑。
    • useKeyboard:监听 delete、ctrl+z、ctrl+shift+z 并调用对应 dispatch。
  8. 性能:
    • 仅渲染可视区域(虚拟化);
    • 选中态用 CSS 类名切换,避免重生成 React 元素;
    • 高频 mousemove 用 requestAnimationFrame 节流。
  9. 数据持久化:DSL 序列化为 JSON 存入后端或本地 IndexedDB,刷新后恢复。
  10. 扩展:后续加锁、组合、对齐线、动画编排,均通过扩充 DSL 字段与 reducer case 完成,不破坏原有逻辑。

答案

以下示例用 150 行左右代码给出最小可运行方案,采用“JSON DSL + 受控渲染 + 不可变更新”模式,支持点选、删除、置顶/置底。生产环境可继续拆 Hook、加虚拟化、补撤销重做。

// types.ts
export interface Node {
  id: string;
  type: 'rect' | 'text';
  x: number;
  y: number;
  w: number;
  h: number;
  z: number;        // 冗余字段,方便调试
  [key: string]: any;
}

export interface CanvasState {
  nodes: Node[];
  selectedIds: Set<string>;
}
// CanvasContext.tsx
import React, { createContext, useContext, useReducer, useCallback } from 'react';
import type { Node, CanvasState } from './types';

type Action =
  | { type: 'SELECT'; id: string; multi: boolean }
  | { type: 'DELETE' }
  | { type: 'MOVE_LAYER'; direction: 'top' | 'bottom' | 'up' | 'down' };

const init: CanvasState = {
  nodes: [
    { id: '1', type: 'rect', x: 50, y: 50, w: 100, h: 80, z: 0 },
    { id: '2', type: 'text', x: 200, y: 100, w: 120, h: 40, z: 1 },
  ],
  selectedIds: new Set(),
};

function reducer(state: CanvasState, action: Action): CanvasState {
  switch (action.type) {
    case 'SELECT': {
      const { id, multi } = action;
      const next = new Set(state.selectedIds);
      if (multi) {
        next.has(id) ? next.delete(id) : next.add(id);
      } else {
        next.clear();
        next.add(id);
      }
      return { ...state, selectedIds: next };
    }
    case 'DELETE': {
      if (state.selectedIds.size === 0) return state;
      const remain = state.nodes.filter(n => !state.selectedIds.has(n.id));
      return { ...state, nodes: remain, selectedIds: new Set() };
    }
    case 'MOVE_LAYER': {
      if (state.selectedIds.size === 0) return state;
      const nodes = [...state.nodes];
      const ids = Array.from(state.selectedIds);
      // 按当前数组顺序排序,保证移动一致性
      ids.sort((a, b) => {
        const ia = nodes.findIndex(n => n.id === a);
        const ib = nodes.findIndex(n => n.id === b);
        return ia - ib;
      });
      if (action.direction === 'top') {
        // 抽出来再放末尾
        const moved = nodes.filter(n => ids.includes(n.id));
        const rest  = nodes.filter(n => !ids.includes(n.id));
        return { ...state, nodes: [...rest, ...moved] };
      }
      if (action.direction === 'bottom') {
        const moved = nodes.filter(n => ids.includes(n.id));
        const rest  = nodes.filter(n => !ids.includes(n.id));
        return { ...state, nodes: [...moved, ...rest] };
      }
      // up / down 略,逻辑类似相邻交换
      return state;
    }
    default: return state;
  }
}

const CanvasCtx = createContext<{
  state: CanvasState;
  dispatch: React.Dispatch<Action>;
}>(null!);

export const CanvasProvider: React.FC<{ children?: React.ReactNode }> = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, init);
  return (
    <CanvasCtx.Provider value={{ state, dispatch }}>
      {children}
    </CanvasCtx.Provider>
  );
};

export const useCanvas = () => useContext(CanvasCtx);
// Canvas.tsx
import React, { useRef, useEffect } from 'react';
import { useCanvas } from './CanvasContext';

export default function Canvas() {
  const { state, dispatch } = useCanvas();
  const svgRef = useRef<SVGSVGElement>(null);

  useEffect(() => {
    function onKeyDown(e: KeyboardEvent) {
      if (e.key === 'Delete') dispatch({ type: 'DELETE' });
      if (e.key === 't' && e.ctrlKey) dispatch({ type: 'MOVE_LAYER', direction: 'top' });
      if (e.key === 'b' && e.ctrlKey) dispatch({ type: 'MOVE_LAYER', direction: 'bottom' });
    }
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [dispatch]);

  const handleMouseDown = (e: React.MouseEvent, id: string) => {
    const multi = e.shiftKey;
    dispatch({ type: 'SELECT', id, multi });
  };

  return (
    <svg
      ref={svgRef}
      width="800"
      height="600"
      tabIndex={0}
      style={{ border: '1px solid #ccc', outline: 'none' }}
    >
      {state.nodes.map(node => {
        const selected = state.selectedIds.has(node.id);
        return node.type === 'rect' ? (
          <rect
            key={node.id}
            x={node.x}
            y={node.y}
            width={node.w}
            height={node.h}
            fill={selected ? '#1890ff' : '#69c0ff'}
            onMouseDown={e => handleMouseDown(e, node.id)}
            style={{ cursor: 'pointer' }}
          />
        ) : (
          <text
            key={node.id}
            x={node.x}
            y={node.y + 20}
            fill={selected ? '#1890ff' : '#000'}
            onMouseDown={e => handleMouseDown(e, node.id)}
            style={{ cursor: 'pointer', userSelect: 'none' }}
          >
            示例文字
          </text>
        );
      })}
    </svg>
  );
}

使用:

import React from 'react';
import { CanvasProvider } from './CanvasContext';
import Canvas from './Canvas';

export default function App() {
  return (
    <CanvasProvider>
      <Canvas />
    </CanvasProvider>
  );
}

要点回顾

  • 所有状态收敛到 CanvasProvider,组件仅做纯渲染;
  • 选中态通过 selectedIds 派生,不额外存储 DOM 引用;
  • 删除、层级调整都是纯函数,天然可时间旅行;
  • 键盘事件与画布事件分离,方便后续加快捷键提示面板。

拓展思考

  1. 撤销重做:用 useReducer 的 enhancer 模式或 use-undo 库,把每次 dispatch 产生的 patches 存入历史栈;注意合并连续移动操作为一个事务。
  2. 多页文档:把 CanvasState 升级为 Page[],顶层维护 currentPageIndex,切换页面时保留每页独立的选中态与历史栈。
  3. 组合/解组:给 Node 加 children 字段,实现树形结构;选中组合后高亮整个 Group,拖拽时整体移动。
  4. 对齐线:在 mousemove 时扫描其他节点边界,若当前节点边缘与某边界距离 < 阈值,则渲染辅助线并吸附。
  5. 性能优化:
    • 节点过万时使用虚拟滚动(只渲染视口内图形);
    • 选中态用 CSS contain: paint 隔离重绘;
    • WebWorker 计算碰撞检测,避免阻塞主线程。
  6. 协同编辑:基于 OT 或 Yjs,把 DSL 转换为 CRDT 数据,WebSocket 广播操作,冲突自动合并。
  7. 可视化搭建平台商业化:提供物料市场、模板中心、权限管理、一键发布至 CDN,React 侧仅需保证 DSL 规范稳定,即可无缝升级渲染引擎。