【问题标题】:Change Kinetic.Text's text on Group click event在组单击事件上更改 Kinetic.Text 的文本
【发布时间】:2013-04-02 02:43:47
【问题描述】:

刚开始检查动力学 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 的名称。我做错了什么?

【问题讨论】:

    标签: javascript canvas html5-canvas kineticjs


    【解决方案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>
    

    【讨论】:

      猜你喜欢
      • 2015-10-14
      • 1970-01-01
      • 2022-11-25
      • 2018-09-15
      • 2019-03-02
      • 2017-05-25
      • 2020-11-17
      • 2015-12-31
      • 1970-01-01
      相关资源
      最近更新 更多