计算圆的中心以对齐中间的文本

时间:2013-09-07 23:19:57

标签: javascript kineticjs

我有一个围绕画布移动的圆圈。

当用户按下圆圈时,半径从20扩展到100,当它们释放时,它会停止生长。

我想在它的中心显示圆的半径,并随着它的增长而更新。

我的圈子和文字代码如下。我是否需要圆圈的高度和宽度以及文本正确居中的文字,并且圆圈是否仍能正常生长?

var circle = new Kinetic.Circle({
    x : stage.getWidth() / 2,
    y : stage.getHeight() / 2,
    radius : 20,
    fill : 'grey',
    stroke : 'black',
    strokeWidth : 1,
});

var radiusText = new Kinetic.Text({
    x : circle.getX(),
    y : circle.getY(),
    text : '10',
    fontSize : 10,
    height : (circle.getAttr('radius') * 2) / 2,
    width : (circle.getAttr('radius') * 2) /2,
    fontFamily : 'Verdana',
    fill : '#000',
    align : 'center'
});

http://jsfiddle.net/ZQEer/2/

1 个答案:

答案 0 :(得分:1)

X,Y的圆形坐标是中心。文字的X,Y坐标是左上角。您不需要在radiusText中设置宽度和高度。您可以使用offset:

var radiusText = new Kinetic.Text({
    x : circle.getX(),
    y : circle.getY(),
    text : '10',
    fontSize : 10,
    fontFamily : 'Verdana',
    fill : '#000',
    align : 'center'
});
radiusText.setOffset({
    x : radiusText.getWidth()/2,
    y : radiusText.getHeight()/2
});

http://jsfiddle.net/dhH9z/3/