Enhancing SVG G elements with d3.zoom for better scaling and transforming effects on bigger children

I'm facing an issue where the shapes generated inside a G element are larger than the container.

Despite trying different methods, most examples I come across have hardcoded sizes and coordinates. Even when attempting to calculate offsets, the output of zoom.scaleTo() and zoom.translateTo() seems to be different from what I'm inputting.

It appears that scaling with SVG may cause coordinate offsets, which could be the root of the problem.

In a code pen I created, I added two Rects within a G element, which is then appended to another G (referenced as this.g in my code).

You can view the Codepen Here

This is the function where the adjustment needs to take place:

function setUpZoomAndCenterG() {
  let zoom = d3.zoom()
    .extent([
      [0, 0],
      [this.targetDiv.clientWidth, this.targetDiv.clientHeight],
    ])
    .scaleExtent([-1, 8])
    .on('zoom', (e) => {
      this.g.attr('transform', e.transform);
      // console.log(e)
    })

  this.svg.call(zoom);
  
  // Need to center the red boxes and fit them to the window. with a margin of 0.05/5%  it wuld also need to take into account landscape and portrait
  
  // zoom.scaleTo()
  // zoom.translateTo()
}

I expect the output to resemble this: https://i.sstatic.net/cEV9l.png

If anyone has encountered a similar issue before and can guide me through the process, it would be greatly appreciated.

Answer №1

Here is the link to check out what I have added: https://codepen.io/lary-Test/pen/mdQvzgr

var transform = d3.zoomIdentity
    .translate((this.targetDiv.clientWidth / 2), 0).scale(this.targetDiv.clientHeight / (2000/*rect height*/))
    .translate(-2150/*rect with - rect.x*/, -100 /*rect y*/);
this.svg.call(zoom) // Adds zoom functionality
    .call(zoom.transform, transform);

To start off, I horizontally translated half of your total width to center. Then, I scaled your height by dividing it by the rectangle's height so that the rectangles fit perfectly in the zoomed height. Next, I vertically translated to compensate for your rect.y, and horizontally to adjust for the first rect.x and first rect.width, as well as half of your second rect.x.

All values are currently hard coded, but you should be able to make use of variables with this setup.

Best of luck!

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

Commitments when using a function as an argument

While I have a good understanding of how promises function, I often struggle when it comes to passing a function as a parameter: var promise = new Promise(function(resolve, reject) { // Perform asynchronous task ec2.describeInstances(function(err, ...

Function for masking phone numbers is adding additional "x's" to the input field

My phone number formatting script is supposed to add dashes after the third and sixth characters, as well as insert an "x" after the 10th character for extensions. However, it is adding extra "x's" after the 12th character, resulting in the incorrect ...

Accessing form data from Ajax/Jquery in php using $_POST variables

Thank you in advance for any assistance on this matter. I'm currently attempting to utilize Ajax to call a script and simultaneously post form data. While everything seems to be working correctly, the $POST data appears to come back blank when trying ...

executing an SQL query with mysql-npm on the Amazon Web Services platform

Hey everyone, I'm facing a bit of a challenge that I'm struggling to solve. It's kind of a strange issue :/ I've created a Lambda function to connect to a MySQL DB using the 'mysql' node package. When I run the function from ...

Frontend update: Changing the display format for dates

Received from the backend is an array of objects (leavedays)- var leavedays = [{"_id":"62d544ae9f22d","season":2022,"name":"LEAVEDAY1","dateFrom":"2022- 07-26T00:00:00.000Z","date ...

How can we change a jQuery document click function to an inline onclick function?

Under certain circumstances, I have to refactor my click function into a standalone function and trigger it using inline onClick="myFunction();" This is my current code structure: $(document).on('click','.exBtn', function(){ var ex = ...

There was an error while parsing JSON on line 1, where it was expecting either a '{' or '[' to start the input

I've been struggling to extract data from my PHP array that is encoded using json_encode. I'm new to JQuery and have been attempting this for a few days without success. This code snippet is not producing the desired results: $.post('coord ...

The velocity of jQuery selectors

Which is more efficient: using only the ID as a selector or adding additional identifiers? For instance $('#element') vs $('#container #element') or getting even more detailed: $('body div#container div#element') ? ...

Is there a way to obtain HTML code within a contentEditable DIV?

When working in a contentEditable-DIV, my goal is to extract the HTML code from the starting position (0) to the end position where the user has clicked. <div id="MyEditableId" contentEditable="true"> 1. Some text 123. <span style="background-c ...

Navigating through the maze of ES6 imports and dealing with the complexities

Currently, I am delving into React and creating my own components. However, the issue of project organization has arisen. Here is the structure of my project: Project_Folder - Components - Form - index.js - form.less - package.js ...

Prepare the column data for Vue Good-Table by formatting it beforehand

I've created a custom Vue.js component that retrieves orders from a Woocommerce store. These orders include product variations and are received in object form. Before displaying the data in a table, I need to format the object accordingly. This is a ...

Angular - Manipulating the selected option in a select box from the controller

My issue involves a select box that is defined in the following manner: <select ng-model="selectedSupplier" ng-options="supplier.name for supplier in suppliers"> </select> Within my controller, there is a button that doesn't have any r ...

Clicking will cause my background content to blur

Is there a way to implement a menu button that, when clicked, reveals a menu with blurred content in the background? And when clicked again, the content returns to normal? Here's the current HTML structure: <div class="menu"> <div class=" ...

Utilizing the setState method within an 'async function with arguments' for handling onClick events

In my next.js app, I have a file named "temp.js" located in the /pages directory. This is the code inside temp.js: import React from 'react'; import {Button} from '@mui/material'; class SomeClass extends React.Component{ state={ ...

Can we disable hydration warnings for all nested children within a component in NextJS?

Note: I am currently using NextJS 14, but I suspect this issue also exists in NextJS 13. I have created a ThemeToggle component that utilizes the next-themes package. Even if I develop my own version of next-themes using React Context or another state man ...

Stop geocomplete from providing a street address based on latitude and longitude coordinates

Is there a way to prevent geocomplete from displaying the street portion of the address when passing lat and lng coordinates? Here's an example: If I pass these coordinates to geocomplete: var lat = '40.7127744' var lng = '-74.006059& ...

JQuery Mobile: Adding fresh, dynamic content - CSS fails to take effect

I've encountered this issue before, but I'm still struggling to resolve it. When adding dynamic content to a page (specifically a list-view), the CSS seems to disappear once the content is added. I've tried using the trigger("create") functi ...

Set the scroll position to the top left corner (0,0) when a link to the current route is clicked or pressed

In my React application, I am faced with a challenge. When the user is on the route /gallery/images and clicks on a link (such as <a> or <Link> from react-router-dom) that leads to the same route currently being displayed, how can I detect thes ...

Adding a line and text as a label to a rectangle in D3: A step-by-step guide

My current bar graph displays values for A, B, and C that fluctuate slightly in the data but follow a consistent trend, all being out of 100. https://i.stack.imgur.com/V8AWQ.png I'm facing issues adding lines with text to the center of each graph. A ...

Use map.fitBounds in MapBox to continuously adjust the map view to show only the visible features on the map

In my map, there are various features with IDs stored in an array called featureIds. Within my application, I have a button that can toggle the visibility of certain features. To address this toggling behavior, I am developing a JavaScript function named ...