AnyChart / GraphicsJS

A lightweight JavaScript graphics library with the intuitive API, based on SVG/VML technology.
http://www.graphicsjs.org/
BSD 3-Clause "New" or "Revised" License
991 stars 68 forks source link

Placing text? #13

Open amca01 opened 3 years ago

amca01 commented 3 years ago

Hello,

I have just discovered GraphicsJS - and it might be just what I need to create simple fixed graphics for the web. (I'm an academic, and I'm moving from PDF to HTML in the interests of accessibility). However, I often need to center text within a graphics element; say a rectangle. This could be easily done if there was a way of anchoring text by its center, rather than by the top left of its bounding box, I have fiddled with the hAlign parameter but not with much success. So what is the simplest method of centering text within a rectangle?

And also - is there a way of telling GraphicsJS to use the same text as the surrounding web page? And so if the user (or browser) changes the text, that is also reflected in the GraphicsJS output?

I apologise if these are simple questions, but I can't yet answer them myself. Many thanks!

Alasdair

Shestac92 commented 3 years ago

@amca01 The GraphicsJS API doesn't support anchor settings for text elements. You can recalculate the X position of the text knowing its width to add x-offset to place it in the center. For this purpose, you can use getTextWidth() method.

You can apply the text content only by calling text() method. The text element doesn't follow other elements on the page. So, the text can be applied only manually via API call.

amca01 commented 3 years ago

Thank you very much - I can certainly do that. In fact for most of my needs I can simply include an "offset" value which pushes the label where I want it. Clearly though, I should be able to write a small subroutine which I can use myself any time, for centering text around an anchoring point, and I suppose this can be added in the html head section where graphics.js is first called. Although I can program in JavaScript and manage html, I'm still a bit unclear on how they interact. But anyway, thank you again!