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

Calculate the center of a circle to align text in the middle

本文关键字:对齐 文本 在中间 计算      更新时间:2023-09-26

我有一个在画布上移动的圆圈。

当用户将鼠标悬停在圆圈上时,半径从 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/

X, Y 圆坐标是中心。文本的 X,Y 坐标位于左上角。您无需在半径文本中设置宽度和高度。您可以使用偏移量:

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/