简体   繁体   中英

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

I have a circle that moves around a canvas.

When the user mouses down on the circle, the radius expands from 20 to 100 and when they release it it stops growing.

I want to display the radius of the circle in the center of it and have it update as it grows.

My circle and text code is below. Do I need a height and width for the circle and text for the text to center properly, and still have the circle grow properly?

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 coords of circle is center. X,Y coords of text is top left corner. You don't need to set width and height in radiusText. You can use 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM