缩放文本?

获取Konva最新的信息

怎样使用变换工具调整文字宽度?

首先,Konva.Transformer 改变的是节点的 scaleXscaleY 属性。如果你想改变文字的宽度,不需要修改它的大小,你应该将文字的缩放比例重置为1并且相应的调整 width

你可以通过 transform 事件更新文字的属性。

说明:试试缩放下面文字

Konva Text resize Demoview raw
<!DOCTYPE html>
<html>
<head>
<!-- USE DEVELOPMENT VERSION -->
<script src="https://unpkg.com/[email protected]/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 text = new Konva.Text({
x: 50,
y: 60,
fontSize: 20,
text: 'Hello from the Konva framework. Try to resize me.',
draggable: true,
});
layer.add(text);

var MIN_WIDTH = 20;
var tr = new Konva.Transformer({
nodes: [text],
padding: 5,
// enable only side anchors
enabledAnchors: ['middle-left', 'middle-right'],
// limit transformer size
boundBoxFunc: (oldBox, newBox) => {
if (newBox.width < MIN_WIDTH) {
return oldBox;
}
return newBox;
},
});
layer.add(tr);
layer.draw();

text.on('transform', () => {
// with enabled anchors we can only change scaleX
// so we don't need to reset height
// just width
text.setAttrs({
width: Math.max(text.width() * text.scaleX(), MIN_WIDTH),
scaleX: 1,
scaleY: 1,
});
});
</script>
</body>
</html>