KineticJS调整文本大小以适应内部矩形和一些填充

时间:2013-01-15 02:12:56

标签: javascript html5 canvas kineticjs

这是一个链接:http://jsfiddle.net/6VRxE/11/

我有一个固定大小的文本框,我想动态更改文本,文本大小和填充,以便文本适合矩形并垂直对齐。

 var messageText = new Kinetic.Text({
      x: .25*stage.getWidth(),
      y: .25*stage.getHeight(), 
      width: .5*stage.getWidth(),
      height: .5*stage.getHeight(),
      fontSize: 10,
      fontFamily: 'Lucida Grande',
      text: 'Hello, click to continue',
      align: 'center',
      textFill: '#006400',
      stroke: 'gray',
      draggable: true,
      fill: 'white',
 });

我想用一个事件或函数来改变文本:

 messageText.on('click',function(){
      messageText.setText('hi');
      messageText.setFontSize(messageText.getHeight()/2);
      messageText.setPadding(messageText.getHeight()/5); //this was one possibility to do some alignment but doesn't work great
      stage.draw();
  });

有没有人有一个很好的解决方案来计算文字大小取决于长度?

1 个答案:

答案 0 :(得分:2)

查看以下padText功能是否能完成您的目标:

<!DOCTYPE html>
<html>
    <head lang="en">
        <meta charset="UTF-8">
        <title>Text Container Test</title>
    </head>
    <body>
        <div id="container"></div>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/kineticjs/5.0.6/kinetic.min.js"></script>
        <script>
            var layer = new Kinetic.Layer,
                text = new Kinetic.Text({
                    text: 'Fit Me',
                    fill: 'black',
                    align: 'center'
                }),
                rect = new Kinetic.Rect({
                    width: 400,
                    height: 200,
                    stroke: 'red'
                }),
                stage = new Kinetic.Stage({
                    width: rect.width(),
                    height: rect.height(),
                    container: 'container'
                });

            layer.add( text );
            layer.add( rect );

            stage.add( layer );

            padText( text, rect, 10 );

            layer.draw();

            function padText( text, container, amount ){
                while (( text.width() * 1.001 ) < container.width() - ( amount * 2 ))
                    text.fontSize( text.fontSize() * 1.001 );

                text.y(( container.height() - text.height() ) / 2 );

                text.width( container.width() );
                text.height( container.height() );
            }
        </script>
    </body>
</html>

Example