Position PointText in Center of Canvas

1.1k Views Asked by At

I need this:

var text = new PointText({
    point: [50, 50],
    content: 'Text',
    fillColor: 'black',
    fontFamily: 'Courier New',
    fontWeight: 'bold',
    fontSize: 25
});

to be centered (x + y) in my canvas.

There is nothing special about the canvas.

2

There are 2 best solutions below

0
On BEST ANSWER

The view object stores a center property which represents it's centre. So if you do this:

var text = new PointText({
  position: view.center,
  content: 'Text',
  fillColor: 'black',
  fontFamily: 'Courier New',
  fontWeight: 'bold',
  fontSize: 25
});

It will be positioned in the centre of your canvas.

Here's the Sketch as well.

0
On

If you are looking for a more precise positionning, consider centering your text using justification: 'center' and adding a small vertical offset proportional to font size.

var text = new PointText({
    position: view.center + [0,5],
    justification: 'center',
    content: 'Text',
    fillColor: 'blue',
    fontFamily: 'Courier New',
    fontWeight: 'bold',
    fontSize: 25
});

See this Sketch for a demonstration.