Can someone please give me an example on how to center text on a JavaFX 2 Canvas?
GraphicsContext has some functions like setTextAlign, but I am not sure on how to use all those methods and which of them I really need. I want to center my text vertically and horizontally.
To align HTML5 Canvas text, we can use the textAlign property of the canvas context, which can be set to start, end, left, center, or right. The alignment is relative to an imaginary vertical line at the x position of the text defind by fillText() or strokeText().
If you are selecting more than one item, check the “Align to Canvas” box in the design tab of the inspector panel. Choose the align left, center, or right, or the top, middle, or bottom icons to align objects respectively to the canvas.
Center the text vertically between the top and bottom margins. Select the text that you want to center. in the Page Setup group, and then click the Layout tab. In the Vertical alignment box, click Center.
How do I vertically align text in canvas? To vertically align text with HTML5 Canvas, we can use the textBaseline property of the canvas context. textBaseline can be set with one of the following values: top, hanging, middle, alphabetic, ideographic, and bottom.
Here is a sample:
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.VPos;
import javafx.scene.*;
import javafx.scene.canvas.*;
import javafx.scene.layout.StackPane;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
public class TextCanvas extends Application {
@Override public void start(Stage primaryStage) {
Canvas canvas = new Canvas(175, 40);
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setTextAlign(TextAlignment.CENTER);
gc.setTextBaseline(VPos.CENTER);
gc.fillText(
"Text centered on your Canvas",
Math.round(canvas.getWidth() / 2),
Math.round(canvas.getHeight() / 2)
);
StackPane layout = new StackPane();
layout.getChildren().addAll(canvas);
primaryStage.setScene(new Scene(layout));
primaryStage.show();
}
public static void main(String[] args) { launch(args); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With