Discover the method of utilizing getElementById in conjunction with getBBox to ascertain the dimensions of an SVG in width and

Having obtained a D3JS tree and successfully saved it as an SVG file, my goal is to adjust the viewBox size based on the svg box size for better visualization. Suggestions include using getElementById along with getBBox.

I am struggling to correctly pass the svg content to getElementById, resulting in receiving null for any input I provide.

To test my code, I attempted it with a standard D3JS tree example to try out the functions but still couldn't grasp their usage.

The select statement for my svg is:

 var svg = d3.select("div.svg-container-ar").append("svg")
    .attr("width", width + margin.right + margin.left)
    .attr("height", height + margin.top + margin.bottom)
    .call(zoom)
    .on("wheel.zoom", null) 
    .on("dblclick.zoom", null)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")scale(.7,.7)");
    zoom.translate([margin.left, margin.top]).scale(.7); 

My attempt at using getElementById that results in null:

// This event is used to download SVG document
   $('#download-SVG').click(function() {
   var svgElement = document.getElementById('svg');
   // console.log(svgElement);
   let {width, height} = svgElement.getBBox();
   .
   .
   }

I would greatly appreciate any guidance on this issue, or if there exists another method to achieve the variable viewBox size requirement.

Answer №1

function prepareDownload(svgEl) {
  // Access the bounding box of the SVG element.
  // In certain scenarios, you may need to get the bbox from an inner <g> element
  // where the actual shapes reside.
  const bBox = svgEl.node().getBBox()
  // Set the viewBox of the SVG to match the bbox
  svgEl.attr("viewBox", `${bBox.x} ${bBox.y} ${bBox.width} ${bBox.height}`)
  // Call the save function (may not work on Stackovertflow's sandbox)
  saveSvg(svgEl.node(), 'my-svg.svg')
  // Remove the viewBox to ensure it appears as usual on screen
  svgEl.attr('viewBox', null)
}

function saveSvg(svgEl, name) {
  svgEl.setAttribute("xmlns", "http://www.w3.org/2000/svg")
  const svgData = svgEl.outerHTML
  console.log(svgData)
// Create a blob containing the XML declaration and SVG data
  const preface = '<?xml version="1.0" standalone="no"?>\r\n'
  const svgBlob = new Blob([preface, svgData], {type:"image/svg+xml;charset=utf-8"})
  // Generate URL for the Blob
  const svgUrl = URL.createObjectURL(svgBlob)
// Create a download link and trigger the download
  const downloadLink = document.createElement("a")
  downloadLink.href = svgUrl
  downloadLink.download = name
  document.body.appendChild(downloadLink)
  downloadLink.click()
  document.body.removeChild(downloadLink)
}
// Add event listener to button for triggering download
document.querySelector('button').addEventListener("click", function() {
  prepareDownload(d3.select("svg"))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<button>Download</button>
<svg>
  <circle style="fill: #69b3a2" stroke="black" cx=50 cy=50 r=40></circle>
</svg>

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

Exploring the Plaid QuickStart demo in JavaScript

I'm encountering an issue while trying to implement Plaid functionality in a JavaScript environment. Despite following the documentation, I am unable to get it to function as expected. Initially, I create a link token using Node.js with the following ...

Having difficulty passing an array list from JavaScript to a Django View

I am struggling with handling an array called tableData in Python. Despite using print(pieFact), I am not seeing any output on my terminal. Additionally, when I include 'test': tableData within var data = {'test': '2', csrfmid ...

PHP code for updating and modifying images

Is it possible to dynamically call an image using PHP? For instance, I have a homepage with one div for an image (pic1) and after two weeks, I want to change the image to (pic2). How can I achieve this without accessing my cpanel to modify the code manua ...

Error: Attempting to access the 'SearchBox' property of an undefined variable is not allowed

I have been working on a Google Maps code that displays both public and private schools with different markers for each category. However, when running the code, I encountered an error specifically on this line of code: var searchBox = new google.maps.pl ...

I am facing difficulty in accessing information from my API through Angular

I recently developed an API using NodeJS. While attempting to fetch data from the API using AngularJS, I encountered an issue where no data is being displayed. Take a look at my API, which contains data in JSON format. You can access the live link to ...

Is it possible to apply the active class to the current list menu item in Mark using server-side techniques instead of client-side JS

When a menu item is clicked, I want to add the active class to that specific menu item. For example, if someone clicks on the contact page, the contact option in the menu should receive the active class. I am currently working with NodeJS and Koa. Below is ...

Upgrade the jQuery code from version 1.4.2 min to version 1.10.2 min

Hey there, I'm looking for assistance with updating the code below to use jQuery 1.10.2. The backslashes are present because I am using it with PHP and need to escape special characters. I'm not very familiar with JavaScript and unsure of the ch ...

Using jQuery, retrieve JSON data from a different domain URL, even if the JSON data is not well-structured

Currently, I am utilizing jQuery's ajax function to access a URL from a different domain which returns JSON data. During my testing phase, I've encountered an issue where the presence of multiple '&quot' strings within the JSON valu ...

Is your list rendering in Vue.js with AJAX ready to go?

At this moment, my Vue.js component is retrieving data from an Elasticsearch query and displaying it in a list like this: <li v-for="country in countries">{{ country.key }}</li> The issue I am facing is that I want to show users only a snippe ...

Tips for integrating Laravel's blade syntax with Vuejs

Can you guide me on integrating the following Laravel syntax into a Vue.js component? @if(!Auth::guest()) @if(Auth::user()->id === $post->user->id) <a href=#>edit</a> @endif @endif ...

Refusing to cease downloading music on the local server through the embedded audio element

I was trying to setup background music on my website, but when I test it localhost, the music download instead of playing. However, when I tested with the full path, it played as expected. How can I prevent the download from happening in localhost? Here i ...

Using `b-form-input` to toggle the visibility of the password using `v-bind:type`

Utilizing bootstrap.vue components, specifically "b-form-input", I am trying to implement a feature to hide and show the password by clicking the button attached to the input field. While this functionality works with a regular input field, I am facing cha ...

Linking a watcher property to control the opacity value of inline styles

Struggling to connect the opacity of a div with the value of a slider. <div class="container" v-bind:style="opacity">test content</div> Despite my efforts, I can't seem to make the binding work correctly. When I check in the developer to ...

What is the best way to link a variable to a specific property within a

I am facing an issue with adding data from the server to a JSON property and displaying it. I know that JSON only accepts primitive types, so how can I dynamically add data to a JSON property? For instance, in the code snippet below, I am trying to assign ...

Ways to implement variables in Jade that are transmitted through res.render

Firstly, I would like to apologize for any errors in my English. In my router file, I have the following code: exports.index = function (req, res) { res.render('./game/main', {name:req.session.name, menuOp:'Home'}); } Additionally, ...

What is the best way to make my if statement pause until a GET request finishes (GUARD) with the help of Angular?

I am currently working on implementing admin routes for my Angular app, and I have used a role guard to handle this. The code snippet below showcases my implementation: However, I would like the get request to finish executing before the if statement begi ...

Unable to establish a connection with the Mongo Database

Apologies if this issue seems like a beginner one (I'm new to this platform)... I've been attempting to configure my application to connect to the database, but I keep encountering an error and I can't pinpoint the problem. Here's the ...

The Ionic search bar will only initiate a search once the keyboard is no longer in view

In my Ionic application, I have implemented a search bar to filter and search through a list. The filtering process is triggered as soon as I start typing in the search bar. However, the updated results are not displayed on the screen until I manually hide ...

Utilizing Ajax for Django POST Requests

I have an app called register_login which handles login and registration operations. On my localhost:8000/login page, I have a form and I want the button to redirect to a function in the register_login app. However, I am facing difficulties achieving this ...

How can Three.js be used to automatically adjust the camera to fit the entire scene in view?

As I work on setting up my scene and adding geometries, I am struggling with adjusting the camera to view the entire scene. I am specifically trying to incorporate an algorithm that involves bounding boxes, but I have hit a roadblock. ...