画布中绘制图形,并且跟随拖动、缩放

173 阅读1分钟

上文中已经实现了画布的无限拖动和缩放,这次我们在画布中添加图形,让图形跟随者画布一起动起来。如果没看过上篇的可以点这里:juejin.cn/post/728295…

效果展示

codesandbox.io/s/svg-graph…

实现思路

  1. 利用 svg g 元素的 transform 属性来实现移动、缩放;
  2. 移动,这个很简单,这需要记住画布平移总的偏移量即可;
  3. 缩放,需要根据鼠标位置结合图形偏移量来计算新的位置;

实现步骤

  1. 增加 rect 图形
<g transform={`matrix(${matrix.a},${matrix.b},${matrix.c},${matrix.d},${matrix.tx},${matrix.ty})`}
>
    <rect
        opacity="1"
        x={0}
        y={0}
        width={rectSize}
        height={rectSize}
        fill="red"
    />
</g>
  1. 状态定义
const [matrix, setMatrix] = useState({
    a1,
    b0,
    c0,
    d1,
    tx50,
    ty0
}); // 图形 transform 参数
  1. 增加拖动代码
const handleMouseMove = (e: any) => {
    // ...
    setMatrix({
      ...matrix,
      ...{ tx: matrix.tx + offsetX, ty: matrix.ty + offsetY }
    });
  };
  1. 增加缩放函数
const zoomShape = (factor: number, center: any) => {
    // 鼠标位置
    let cx = center.x;
    let cy = center.y;
    const tx = toFixed(cx - (cx - matrix.tx) * (factor / scale));
    const ty = toFixed(cy - (cy - matrix.ty) * (factor / scale));

    setMatrix({
        ...matrix,
        ...{
            a: factor,
            d: factor,
            tx,
            ty
        }
    });
};

至此,我们已经完成了画布的绘制,平移,缩放,已经图形的平移、缩放,下一章将继续实现图形的拖动功能。