如何使用konva.js将文本放入rect中?

时间:2019-03-18 18:28:59

标签: javascript web text konvajs

我有一个带有rect的项目,我需要在其中添加文本。有Konva班吗? 我尝试使用Konva.group(),标签...

这是我的最后一次尝试,一开始文字保持原样,但在移动Rect时位置未更新。

var rect = new Konva.Rect({
  x: 20,
  y: 60,
  stroke: '#123456',
  strokeWidth: 5,
  fill: '#ddd',
  width: 600,
  height: 450,
  shadowColor: 'black',
  shadowBlur: 10,
  shadowOffset: [10, 10],
  shadowOpacity: 0.2,
  cornerRadius: 10,
  draggable: true,

})

var complexText = new Konva.Text({
  x: ((rect.attrs.width + rect.attrs.x) - 300)/2 ,
  y: ((rect.attrs.height + rect.attrs.y))/2,
  text:
  "COMPLEX TEXT\n\nAll the world's a stage, and all the men and women merely players. They have their exits and their entrances.",
  fontSize: 18,
  fontFamily: 'Calibri',
  fill: '#555',
  width: 300,
  height:300,
  align: 'center',
  draggable: true,


});

2 个答案:

答案 0 :(得分:1)

var width = window.innerWidth;
var height = window.innerHeight;
var stage = new Konva.Stage({
    container: 'container',
    width: width,
    height: height,
    draggable: true
});

var rectangleLayer = new Konva.Layer();
 
function spawnRectangle(angle){
    var rectangle = new Konva.Group({
        x: 25, 
        y: 25, 
        width: 130,
        height: 25,
        rotation: angle, 
        draggable: true,
    }); 

    rectangle.add(new Konva.Rect({
        width: 130,
        height: 25,
        fill: 'lightblue'
    }));

    rectangle.add(new Konva.Text({
        text:'123',
        fontSize: 18,
        fontFamily: 'Calibri',
        fill: '#000',
        width: 130,
        padding: 5,
        align: 'center'
    }));
    rectangleLayer.add(rectangle);
    stage.add(rectangleLayer);
}
body {
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #D3D3D3;
    background-size: cover;
 }
 
#desc {
    position : absolute;
    top: 5px;
    left: 5px;
}
<script src="https://unpkg.com/konva@4.0.18/konva.min.js"></script>
 
<body>
    <div id="container"></div>
    <div id="desc">
          <button onclick="spawnRectangle(0)">spawn rectangle</button>
          <button onclick="spawnRectangle(90)">spawn rotated rectangle</button>
    </div>
</body>

答案 1 :(得分:0)

您的选择是:

  1. 使用Konva.Label
  2. 创建一个内部包含矩形和文本的可拖动组
  3. 创建一个自定义形状。在sceneFunc
  4. 内绘制矩形和文本