Modify the Viewbox to encompass an svg component

Currently, I am working on creating a map using SVG where users can zoom into a specific area within the SVG, such as a state or country. I came across a helpful tutorial that demonstrates this functionality along with animation. The tutorial can be found here: https://css-tricks.com/interactive-data-visualization-animating-viewbox/ You can also view their codepen example here: https://codepen.io/sdras/pen/512230ed732f9b963ad3e50c8d4dcbb8

However, I am facing issues when trying to replicate this behavior with my own SVG. When I specify to zoom into a particular area, it ends up zooming into a different region instead. Despite attempting to mimic their code structure exactly, I have not been successful. It seems like the problem may lie within my own SVG file.

Here is an excerpt from my HTML:

<svg id="foo" xmlns="http://www.w3.org/2000/svg" 
xmlns:xlink="http://www.w3.org/1999/xlink"  viewBox="0 0 1440 776">

There is a lot more code necessary for this project which I cannot paste entirely here due to its length.

SASS snippet:

html
  body
    svg
      width: 100vw
      height: 100vh

JQuery script:

var test = document.getElementById("_x32_");
console.log(test);
var s = test.getBBox();

//check the console for the SVGRect object
console.log( s );

//we store the values from the object as our new viewBox string
var newView = "" + s.x + " " + s.y + " " + s.width + " " + s.height;
console.log(newView);
//we then set the new viewBox string as the viewBox attribute on the SVG
var foo = document.getElementById("foo");
console.log(foo);
//foo.setAttribute("viewBox", newView);

You can access my CodePen implementation here: https://codepen.io/mat148/pen/xqWMXR

Answer №1

Your issue arises from the fact that the bounding box returned by getBBox() only represents the bounds of the coordinates of the element before any transformations applied by its ancestor elements.

Upon examining the file, it is evident that the element's parentage is structured as follows:

<svg>
  <g id="north-america" transform="translate(100.000000, 45.000000)">
    <polygon id="_x32_" ...>

In this specific case, the element is actually positioned 100 units to the right and 45 units down from the position indicated by the result of getBBox().

By manually adjusting for these offsets, you can observe that it functions correctly.

Naturally, this manual tweak is not a universal solution.

Solving this problem may not be straightforward, but here are some potential approaches you could explore:

  1. Edit the SVG file to eliminate all transforms, applying them directly to the paths and polygons instead. A discussion on achieving this with Inkscape is available in this Stack Overflow thread.

  2. RaphaelJS library likely offers a function that can provide the transformed bounding box. Review the documentation for Element.getBBox() for more information.

  3. If necessary, create a duplicate of the element and its ancestors within a separate <svg> tag, then use getBBox() on this isolated <svg> structure. Essentially, recreate a simplified version of the SVG described earlier (

    <svg><g..><polygon>
    ).

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

What is the significance of keyframes in CSS animations at different percentages

I'm facing a challenge with the code below that is intended to make objects float from left to right in the background. However, once they go off-screen, a vertical scroll bar appears despite the overflow-y: hidden attribute added to the class. I atte ...

Accordion Element using HTML and CSS

Seeking assistance with a website project! I am in need of help in implementing the following feature: I would like the "About" link to expand into a panel when clicked, and retract back when the user clicks "hide" within the panel. Check out the attached ...

Splitting array elements into arguments separated by commas on Node.js

If I have a function that can take a varying number of arguments, with the last one being a callback: xyz.add('item1', 'item2', ..., 'item10', callback) { ... } This code looks messy. I would like to be able to separate ...

My task is to automate the PDF document in Internet Explorer

Performing PDF tasks is something new to me. Whenever I click on the view link, the PDF document opens up and I have to save it to verify. Unfortunately, there is no download option available for me. https://i.sstatic.net/Dz5lB.png When I click on view P ...

Crafting artistic shapes using the Canny Edge Detection technique on Canvas

Can someone provide some guidance on using Canny Edge Detection to generate shapes in Canvas? ...

Transform the CSS to a Mat-Form-Field containing a search box within it

I am currently working with Angular, Angular Material, and SCSS for my project. Here is the front-end code snippet that I am using: <mat-form-field class="custom-form-field" style="padding-top: 5px;padding-bottom: 0px; line-height: 0px; ...

Find the item that has a specific value in its sub-property

Information Models: public class Header{ public int Identifier; public int value; public bool anotherValue; public List<Trailer> trailers; } public class Trailer{ public int ID; public Language MyLanguage; public string ...

Is it feasible to assign a PHP $_SESSION variable to a JavaScript variable?

In my computing class, I am working on a game where the user needs to adjust settings for their robot before starting to play. I have created a separate PHP file for users to customize their robot's settings. I am curious if there is a way to assign ...

Achieving proper form alignment through Bootstrap

Is there a way to create a form that looks like the one shown in the picture, where regardless of the length of the variable names (Name, Mobile, Gender, Age), all value receiving blocks are the same size and aligned vertically? My initial approach involv ...

Discover Headphones with Ionic

Is there a way to detect if headphones are connected to a mobile device (specifically an iPhone) using Ionic? Our Ionic app plays sound normally without headphones, but encounters issues when headphones are plugged in. When you start the app without headp ...

When crafting an XPATH expression, I am able to navigate within the #document element. Within this element, I must specify the path to the HTML body of my web page

I need assistance with my HTML page, can someone please help? Here is the XPath code I am using: (//span[text()='Information']//following::div[contains(@class,'edit-area')])[1]/iframe However, when I run my script, it says that there ...

Executing a function with the initial click

Is there a way to run a function only on the first click, without having it run every time? I already have another function running on window.onload, so I can't use that. Both functions work fine independently, but not together. Right now, I'm ca ...

Implementing dynamic style attachment within a map array function

I am looking to dynamically assign colors to my react component Here are the specific colors I would like to use for this purpose this.color = ["#E91E63", "#2196F3", "#FDD835"] Currently, I am mapping an array in JSX similar to this example { th ...

Tips for creating a new terminal window and interacting with it?

I have a node server that generates logs of activities in the terminal. To have more control over the server during runtime, I aim to integrate a repl server within it. However, I need to ensure that the logs and repl server do not interfere with each ot ...

PHP does not automatically escape HTML special characters

Within my ZF2 application, there is a .phtml layout that includes the following code: <p>Created in 2015 <?php echo htmlspecialchars("by Jérôme Verstrynge",ENT_HTML5); ?></p> However, when I review the source of the pages returned by ...

Create pathways for direct access

I've been studying some code written by someone else to improve my understanding. The way they are setting up routes seems a bit unclear to me. app.use('/dist', express.static(path.join(CURRENT_WORKING_DIR, 'dist'))) // mount rou ...

What is the recommended approach for passing parameters to a JavaScript function from an anchor tag?

I recently came across this intriguing question: What is the best practice for using Javascript and Anchor Tags? The suggestion provided in response to this query involves utilizing the following code snippet: <a id="foo" href="#">Click Me</a&g ...

Modify the background color of the <li> element without using JavaScript after 3 seconds

Is it possible to change the background color of a <li> element without using javascript or JQuery, only with CSS? I've seen incredible things done with CSS alone and believe this is achievable. My <li> element functions as a horizontal m ...

Cycle through every jQuery selector individually

Struggling with some calculations on my website application. Here's the situation: This is the structure of my HTML code: <table> <tr> <td><span class="sub_total">10</span></td> </tr> <tr& ...

What types of mobile browsers, devices, and operating systems are currently compatible with HTML 5, CSS3, and jQuery?

Which mobile browsers, devices, and OS versions are currently compatible with HTML 5, CSS3, and jQuery? ...