Skip to main content

HTML5 Canvas 图形缩放与变换限制

若要限制或改变缩放及变换的行为,你可以使用 boundBoxFunc 属性。 它的工作方式与 dragBoundFunc 有些类似。

使用说明:尝试调整一个图形的大小,你会看到它的宽度被限制在200以内。

此外,你还可以逐个控制每个锚点的移动。请参阅 Resize Snap Demo

import Konva from 'konva';

const width = window.innerWidth;
const height = window.innerHeight;

const stage = new Konva.Stage({
  container: 'container',
  width: width,
  height: height,
});

const layer = new Konva.Layer();
stage.add(layer);

const rect = new Konva.Rect({
  x: 50,
  y: 50,
  width: 100,
  height: 100,
  fill: 'yellow',
  stroke: 'black',
  draggable: true,
});
layer.add(rect);

const tr = new Konva.Transformer({
  nodes: [rect],
  boundBoxFunc: (oldBox, newBox) => {
    // 限制缩放

    if (newBox.width > 200) {
      return oldBox;
    }
    return newBox;
  },
});
layer.add(tr);