Determine the coordinates of a bounding box based on the SVG text object's position

Currently, I am puzzled by how SVG.js calculates the precise x and y coordinates of the corrected bounding box (top left corner) from an SVG text object.

This is how my SVG object appears:

<svg  xmlns="http://www.w3.org/2000/svg" width="266" height="59" viewBox="0 0 266 59">
  <text id="TText" data-name="TText" fill="#707070" font-size="50" font-family="Boogaloo"><tspan x="0" y="0">TText</tspan></text>
</svg>

When I incorporate this code into SVG.js script, the position seems to be y-offset by 11 pixels. I believe this adjustment may be due to the baseline positioning in SVG. Could someone shed light on the calculation process for bounding box x and y coordinates? I attempted to unravel this mystery by delving into the SVG.js repository, but unfortunately, came up empty-handed.

I suspect that the calculations are influenced by the font type. If so, how can one extract this information from a font file?

Below is the code snippet with my SVG.js implementation revealing the accurate X, Y bounding box coordinates:

var draw = SVG().addTo('body');
var text = draw.text('TText');
text.font({
  family: 'Boogaloo',
  size: 50,
});
console.log(text.bbox());

Answer №1

Essentially, our method involves utilizing the browser API to obtain the bounding box (el.getBBox()). The bbox() function acts as a straightforward wrapper for this process. When dealing with text elements, we opt not to calculate a precise adjusted bounding box. Instead, there's some clever trickery at play when it comes to moving text around – typically moved based on its baseline, but we've standardized the API so that all shapes are shifted from their top left corner.

If you're curious about how browsers determine the bounding box of text, check out this informative answer: reproduce Bounding Box of text in Browsers

In short, the numerical results can vary across different browsers. And naturally, having the appropriate font file is crucial.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

CSS - Ensure the parent stays open and the submenu remains highlighted upon selection

I have integrated a CSS Vertical menu with submenus into an ASP.Net application on the master page. Clicking on each menu item directs to different aspx pages. However, when clicking on a submenu within an expanded parent menu, the page redirects as expect ...

What is the process for invoking an asynchronous cleanup function?

Is it possible to trigger an async cleanup function within useEffect? useEffect(() => { return () => Voice.destroy().then(Voice.removeAllListeners); }, []); Keep in mind that the EffectCallback requires a return of void, not Promise<void> ...

Utilizing Node.js to Retrieve a POST Request JSON and Modify its Format

Received an incoming Post request in JSON format like this: [{"username":"ali","hair_color":"brown","height":1.2},{"username":"marc","hair_color":"blue","height":1.4},{"username":"zehua","hair_color":"black","height":1.8}] Need to transform it into the f ...

What is the best way to send ServerSideProps to a different page in Next.js using TypeScript?

import type { NextPage } from 'next' import Head from 'next/head' import Feed from './components/Feed'; import News from './components/News'; import Link from 'next/link'; import axios from 'axios&apo ...

Updating the logic for reconnection when the connection is closed in MySql's X DevAPI can be achieved by utilizing the @mysql/xdevapi module

I am currently utilizing the X DevAPI of MySql v8.0.33 with the @mysql/xdevapi v8.0.33 package. Although I have implemented a reconnect logic, it doesn't seem to be functioning as expected. Here is the code snippet: const mysqlx = require('@mysq ...

Obtain decrypted information from the token

I am facing difficulty in retrieving decrypted user data for the current user. Every time a user logs in, they receive a token. After logging in, I can take a photo and send it to the server. Looking at my code, you can see that this request requires a to ...

Label button for personalized file selection field

Looking to create a unique file selector button instead of the standard <input type='file'/>. The goal is to have a clickable button that performs the same action. <input style={{ display: 'none&ap ...

Leverage the source code of Angular 2 in your project for seamless integration

Currently in the process of setting up Angular with npm: npm install @angular... Encountering an issue where the TypeScript source files are not included. I would like to have access to debug the code using the TypeScript source files (with source maps). ...

Reanimated 2 couldn't generate a worklet - did you accidentally overlook adding Reanimated's babel plugin? The JavaScript engine in use is Hermes

I'm encountering an issue with React-native-Reanimated. I keep getting the error message "Reanimated 2 failed to create a worklet, maybe you forgot to add Reanimated's babel plugin?, js engine: hermes" However, I've already followed the st ...

Is there a browser that enables me to methodically go through network requests individually?

I am currently seeking a way to identify which network requests on my webpage are causing an issue. (Alternatively, I am looking for a method to remotely guide someone through this process.) Are there any browsers that provide the ability to "step through ...

The v-for loop seems to be malfunctioning in my Nuxt 3 project

I have a script with mock data stored in a variable named whatsHappeningItems, and I am trying to pass this data as a reference to a card component using v-for="whatsHappening in whatsHappeningItems". However, when I do this, I encounter the following erro ...

Leveraging external Javascript files in Ionic framework version 3 and above

Hey there, I'm currently working on integrating the Mapwize SDK, an external Javascript library, with the latest version of Ionic. I've encountered the common challenge of getting Javascript to function smoothly with Typescript. Although I'm ...

Error: The route cannot be established within an asynchronous function

The following code snippet is from the api.js module, responsible for creating a test route: 'use strict'; module.exports = function (app) { console.log("before route creation"); app.get("/api/test", (req, res) => { ...

What causes SVG files to appear tilted when rendered in Processing?

My goal is to recreate the classic Freecell card game that was originally designed for Windows XP and make it compatible with Windows 10 using Processing 3. To achieve this, I sourced a set of SVG files from this site that closely resembled the appearanc ...

Converting document.querySelector into a user-friendly format with React hooks

Is there a way to convert the process of fetching an element using querySelector and adding a reference to a div using document.querySelector into something that can be done with React hooks? import ReactDOM from "react-dom"; import h337 fro ...

Tips for preventing the colors of all buttons from changing when only one is clicked in JavaScript

const tasks = `[{ "taskName": "Task 1", "image": "./images/task1.jpg", "description": "Task 1 description", "importance": 0 }, { "taskName": "Task 2", "image": "./images/task2.jpg", "description": "Task 2 description", ...

How can I incorporate a new function into a TypeScript class that already exists?

In my current angular 2 cli project, I am faced with the task of defining a plugin that does not have its own type definition. This plugin relies on a main library that already has its own typed definitions and is functioning properly. I have two files; t ...

The integration of Angular and Node API within the IISNode directory structure is experiencing functionality issues

Read more about the question I have successfully set up my Node API and Angular component with IISnode. However, when accessing the application from the IIS server, I noticed that they are showing in different directories (see image below). Additionally, I ...

Acquiring profile information in intricate scenarios using passport-facebook with node.js

I'm currently working with the passport-facebook package, but I've encountered an issue with the way it's usually implemented: app.get('/oauth/facebook', passport.authenticate('facebook', {})); This approach doesn' ...

Showing an image based on the selected value from a dropdown menu using jQuery

I am trying to dynamically display the correct image based on the option selected in a dropdown menu. Currently, I am able to show the image if the option value matches the filename; however, I need help with displaying the image using echo rather than t ...