在组点击事件上更改Kinetic.Text的文本

时间:2013-04-01 18:02:52

标签: javascript canvas html5-canvas kineticjs

刚刚开始检查kinetic js。我有很多小组,每个小组都有一个Kinetic.Text和一个Kinetic.Rect

我可以通过此提示轻松更改任何文字;

text.on('click', function(evt) {
          this.setText(prompt('New Text:'));
          layer.draw(); //redraw the layer containing the textfield
        });

但我想根据文字更改矩形(包含文本)的高度和宽度。所以,这就是我尝试过的,但这不起作用。它向我显示提示但不更改文本,之后我的组也变得无法点击!;

 group.on('click', function(evt) {
              this.get('.textbox').setText(prompt('New Text:'));
              //this.get('.rectangle')....change rect's height/width here
              layer.draw(); //redraw the layer containing the textfield
            });

矩形和文本框是每个组中Kinteic.TextKinetic.Rect的名称。我做错了什么?

1 个答案:

答案 0 :(得分:1)

您可以使用Kinetic的getTextWidth()来查看文本的宽度。然后调整矩形。

这是代码和小提琴:http://jsfiddle.net/m1erickson/MZCCA/

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <div id="container"></div>
    <button id="fitText">Fit text in the rectangle</button>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.3.0-beta2.js"></script>
    <script>

        $("#fitText").click(function(){ redraw();})

        function redraw(){
            var textWidth=text.getTextWidth();
            // redraw the container--add 10px because the text has 5px padding
            container.setWidth(textWidth+10);
            layer.draw();
        }

        var stage = new Kinetic.Stage({
          container: 'container',
          width: 400,
          height: 200
        });
        var layer = new Kinetic.Layer();

        var container = new Kinetic.Rect({
          x: 100,
          y: 30,
          width: 75,
          height: 30,
          fill:"yellow",
          stroke: 'black',
          strokeWidth: 4,
          draggable: true
        });

        var text = new Kinetic.Text({
          x: 100,
          y: 30,
          text: 'Here is some text.',
          fontSize: 18,
          fontFamily: 'Calibri',
          fill: '#555',
          padding: 5,
          align: 'center'
        });

        layer.add(container);
        layer.add(text);
        stage.add(layer);

    </script>
  </body>
</html>