HTML5 Canvas 形状调整大小和变换限制

如何限制形状的大小变化?

要限制或更改调整大小和变换的行为,您可以使用 boundBoxFunc 属性。
它的工作方式有点类似于 dragBoundFunc

说明:尝试调整形状的大小。您将看到它的宽度限制为 200。

您还可以单独控制每个锚点的移动。请参见 调整大小快照演示

Konva Shape transform and selection Demoview raw
<!DOCTYPE html>
<html>
<head>
<!-- USE DEVELOPMENT VERSION -->
<script src="https://unpkg.com/konva@9.3.18/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Transform Limits Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
</style>
</head>

<body>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;

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

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

var rect = new Konva.Rect({
x: 160,
y: 60,
width: 100,
height: 90,
fill: 'red',
name: 'rect',
stroke: 'black',
draggable: true,
});
layer.add(rect);

var MAX_WIDTH = 200;
// create new transformer
var tr = new Konva.Transformer({
boundBoxFunc: function (oldBoundBox, newBoundBox) {
// "boundBox" is an object with
// x, y, width, height and rotation properties
// transformer tool will try to fit nodes into that box

// the logic is simple, if new width is too big
// we will return previous state
if (Math.abs(newBoundBox.width) > MAX_WIDTH) {
return oldBoundBox;
}

return newBoundBox;
},
});
layer.add(tr);
tr.nodes([rect]);
</script>
</body>
</html>