如何在KineticJS Wedge中垂直居中文字?

时间:2013-12-18 20:00:53

标签: javascript canvas kineticjs

我有以下代码:

var text = new Kinetic.Text({
    text: carNames,
    fontFamily: 'Calibri',
    fontSize: 17,
    fill: 'black',
    align: 'center'
});
text.toImage({
    width: text.getWidth(),
    height: text.getHeight(),
    callback: function (img) {
        var cachedText = new Kinetic.Image({
            image: img,
            x: 180,
            y: 0
        });
        wedge.add(cachedText);
        layer.draw();
    }
});

生成的楔形和文本如下所示:

enter image description here

但我需要将文本置于楔形内部,如下所示:

enter image description here

有谁知道实现这个目标的方法?我已经尝试了几件事,但我无法像第二张图片那样对齐文本。

提前感谢您的麻烦。

1 个答案:

答案 0 :(得分:2)

一种方法是将文本的偏移量与文本的rotationDeg结合使用:

演示:http://jsfiddle.net/m1erickson/mqsY3/

enter image description here

这是代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Prototype</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.2.min.js"></script>

<style>
body{padding:20px;}
#container{
  border:solid 1px #ccc;
  margin-top: 10px;
  width:350px;
  height:350px;
}
</style>        
<script>
$(function(){

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

    var cx=175;
    var cy=175;
    var wedgeRadius=120;
    var accumAngle=0;

    var center = new Kinetic.Circle({
        x:cx,
        y:cy,
        radius:5,
        fill: 'red'
    });
    layer.add(center);

    for(var i=0;i<12;i++){
        newTextWedge(30,"Element # "+i);
    }

    function newTextWedge(angle,text){

        var wedge = new Kinetic.Wedge({
          x: cx,
          y: cy,
          radius: wedgeRadius,
          angleDeg: angle,
          stroke: 'gray',
          strokeWidth: 1,
          rotationDeg:-accumAngle+angle/2
        });
        layer.add(wedge);

    if(accumAngle>90 && accumAngle<270){
        var offset=[wedgeRadius-10,7];
        var textAngle=accumAngle-180;
    }else{
        var offset=[-50,7];
        var textAngle=accumAngle;
    }

        var text = new Kinetic.Text({
            x:cx,
            y:cy,
            text:text,
            fill: 'red',
            offset:offset,
            rotationDeg:textAngle
        });
        layer.add(text);

        layer.draw();

        accumAngle+=angle;
    }


}); // end $(function(){});

</script>       
</head>

<body>
    <div id="container"></div>
</body>
</html>