javascript - KineticJS 调整文本大小以适应带有一些填充的矩形内部

标签 javascript html 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();
  });

有没有人有一个很好的解决方案来根据长度计算文本大小?

最佳答案

看看下面的 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

关于javascript - KineticJS 调整文本大小以适应带有一些填充的矩形内部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14330136/

相关文章:

javascript - 使用本地存储进行 css 切换开关时遇到问题

javascript - html5 canvas - 是否需要内联定义宽度/高度?

javascript - 不知道如何在 React Native 应用程序中使用 navigation.navigate

javascript - 如何在Material-UI表格中显示动态数据?

javascript - 将 Google Analytics 代码放在 .ASPX 页面中的什么位置?

html - 在表格单元格中,居中 Canvas 元素而不是其兄弟元素

javascript - JS Canvas 中具有随机颜色的同心圆(带循环)?

javascript - 使用主体作为委托(delegate)时选择特定元素

javascript - 在注入(inject)内容脚本之前传递变量

html - Bootstrap 4 Navbar Flex 与 Brand Center 的突破