怎么在缩放图形时保持它的描边宽度?

获取Konva最新的信息

想要改变图形尺寸时不改变它的描边宽度?

首先要明确的是,Konva.Transformer 是改变节点的 scaleXscaleY 属性。

默认情况下,变换图形时,它的描边也会相应的变化。某些场景下这不是我们想要的结果。

这里有两张方法避免描边的缩放:(1)重置图形的 scale 或者 (2)结合使用 shape.strokeScaleEnabled(false)transformer.ignoreStroke(true)

说明:下面两个矩形,绿色的缩放时重置了 scale,红色的关闭了描边的缩放。

Konva ignore strokeview raw
<!DOCTYPE html>
<html>
<head>
<!-- USE DEVELOPMENT VERSION -->
<script src="https://unpkg.com/konva@7.2.5/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Resize Text 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 rect1 = new Konva.Rect({
x: 50,
y: 60,
width: 100,
height: 100,
draggable: true,
fill: 'green',
stroke: 'black',
strokeWidth: 5,
});
layer.add(rect1);

var tr1 = new Konva.Transformer({
nodes: [rect1],
// ignore stroke in size calculations
ignoreStroke: true,
// manually adjust size of transformer
padding: 5,
});
layer.add(tr1);

// first way to skip stroke resize, is just by resetting scale
// and setting width/height instead
rect1.on('transform', () => {
rect1.setAttrs({
width: Math.max(rect1.width() * rect1.scaleX(), 5),
height: Math.max(rect1.height() * rect1.scaleY(), 5),
scaleX: 1,
scaleY: 1,
});
});

// another solution is to use combination of strokeScaleEnabled and ignoreStroke
var rect2 = new Konva.Rect({
x: 250,
y: 60,
width: 100,
height: 100,
draggable: true,
fill: 'red',
stroke: 'black',
strokeWidth: 5,
// do not scale strokes
strokeScaleEnabled: false,
});
layer.add(rect2);

var tr2 = new Konva.Transformer({
nodes: [rect2],
// ignore stroke in size calculations
ignoreStroke: true,
// manually adjust size of transformer
padding: 5,
});
layer.add(tr2);

layer.draw();
</script>
</body>
</html>