What is the process for duplicating a set of elements within an svg file and displaying the duplicate at a specific location?

SVG

<svg width="200" height="200">
    <g id="group">
        <rect x="10" y="10" width="50" height="20" fill="teal"></rect>
        <circle cx="35" cy="40" r="20" fill="red"></circle>
    </g>

    <circle id="ref_cycle" cx="135" cy="140" r="2" fill="green"></circle>

</svg>

I have been using the code below to create a copy of <g id="group"> and display it on the page:

var copy = d3.select("#group").clone(true).attr("transform", "translate(20,00)"); 

Now, I would like the cloned group's center align red "circle" with the center of the "ref_cycle" in the SVG without losing the shape of the group. Can anyone provide guidance on how to achieve this through code?

Thank you in advance.

Answer №1

Below is the code that I have tested and it works, along with some helpful comments for anyone who might need them.

    var referenceCycle = d3.select("#ref_cycle"); 
        //^ Retrieving the reference cycle object

    var cloneTemplate = d3.select("#group"); 
        //^ Getting the template object for later selection and cloning

    var cloneTransX = referenceCycle.attr("cx") - cloneTemplate.select("#inner-ref").attr("cx");
    var cloneTransY = referenceCycle.attr("cy") - cloneTemplate.select("#inner-ref").attr("cy");
        // Adding an ID tag like <circle id="inner-ref"></circle> in the SVG group makes selection easier
        // Calculating the offset between two objects    

    cloneTemplate.clone(true).attr("transform", "translate(" + [cloneTransX, cloneTransY] + ")");
       // Cloning the template object with the calculated translation

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

`Javascript framework suggests ajax navigation as the preferred method`

What is the best way to handle ajax navigation using jQuery? I have recently experimented with a simple jQuery ajax code to implement ajax-based navigation for all the links on a webpage. $('a').click(function(e){ e.preventDefault(); ...

Is there a way to configure eslint to recognize and allow the nullish-coalescing assignment syntax?

The "nullish-coalescing assignment" operator, ??=, has been around for some time now in JavaScript. However, it appears that even newer versions of eslint, like 8.38.0, do not seem to recognize it and throw a syntax error regarding the assignment ...

Error: Attempting to access properties of an undefined object (specifically, the 'prototype' property) within a React application

I encountered an error while working on my React application: TypeError: Cannot read properties of undefined (reading 'prototype') (anonymous function) C:/Users/tatup/Desktop/GrowApp/frontend/node_modules/express/lib/response.js:42 39 | * @pub ...

remove all clicks from jQuery queue

I am facing an issue with a click event that triggers other click events, resulting in the addition of elements to the DOM. EDIT: However, upon clicking it multiple times, additional elements are added each time. Checking the jQuery queue confirms that an ...

Instead of showing the data in the variable "ionic", there is a display of "[object object]"

Here is the code snippet I'm working with: this.facebook.login(['email', 'public_profile']).then((response: FacebookLoginResponse) => { this.facebook.api('me?fields=id,name,email,first_name,picture.width(720).height( ...

When an item in the accordion is clicked, the modal's left side scroll bar automatically scrolls to the top. Is there a solution to prevent this behavior and

When I first load the page and click on the Sales accordion, then proceed to click on Total reported and forecasted sales, the scrollbar jumps back up to the top The marked ng-container is specifically for the UI of Total reported and forecasted sales He ...

I have a task to execute an Ajax request to retrieve and display data from my database table. My approach involves utilizing Perl CGI and attempting to invoke a Perl script using JavaScript

Encountering an issue in the web console with an error in the document.ready function showing an uncaught syntax error unidentified identifier. This CGI script contains JavaScript that calls a Perl script (TestAj.pl) which returns JSON data. I'm atte ...

Tips for monitoring password and password confirmation fields in DevTools when using AngularJS forms

Within the ng-model, I have identified two variables: vm.user.password and vm.confirmpassword. The input fields are equipped with attributes such as id, name, and class. I am interested in monitoring both the password and confirmpassword values within Dev ...

How can I display actual images received as escaped string literals from ExpressJS?

Is there a way to transform this data from ExpressJS into an actual image? The information I'm receiving looks like this instead of an image: {`data: 'PNG\r\n\x1A\n\x00\x00\x00\rIHDR\x00\x00\ ...

Using jQuery to eliminate accepting input from form field

Looking to switch between a URL input and file input based on user selection of a radio button. Encountering an issue when attempting to remove the accept attribute from the input, resulting in an Uncaught TypeError: $(...).get(...).removeAttr is not a fu ...

JS - Activate the ghost element feature by using the preventDefault function

I am currently working on a project where I need to drag elements from a list of img tags to various svg:rect containers. The process involves using mousedown and mouseup events to track which img is being picked from the list and where it is dropped with ...

Relocating JavaScript scripts to an external file on a webpage served by Node.js' Express

When using Express, I have a route that returns an HTML page like so: app.get('/', function(req, res){ return res.sendFile(path.resolve(__dirname + '/views/index.html')); }); This index.html file contains multiple scripts within t ...

"Adding an Image within a Textbox Using Ext JS: A Step-by-Step

How can I add a search image inside a textbox created with the following code? I have created a table with a footer, and within one of the textboxes in the table, I want to include a search button that will call another function when clicked. However, desp ...

Getting Your Redux Form Ready for Submission

I recently transformed my Redux form into a wizard with multiple subcomponents following the structure outlined here: However, I'm encountering difficulties when trying to integrate the form with my actions to submit the form data. Unlike the example ...

Refresh two angular-datatables

I'm facing a challenge when it comes to updating two datatables simultaneously on the same page. Here's how my HTML is structured: <table id="datatable1" ng-if="Ctrl.dtOptions1" datatable="" dt-options="Ctrl.dtOptions1" dt-column-defs="Ctrl. ...

Leveraging the keyword 'this' within an object method in node's module.exports

My custom module: module.exports = { name: '', email: '', id: '', provider: '', logged_in: false, checkIfLoggedIn: function(req, res, next){ console.log(this); } }; I inclu ...

Deleting database information using Jquery when a div is clicked

I'm looking to create an alert system where users will see a pop-up alert on their screen. However, I am facing a major issue in removing the div completely. I understand that I need to remove it from the database, but I'm struggling with finding ...

Having difficulty retrieving objects within a foreach loop of object keys that do not meet the criteria of the string.prototype.replace method

Currently, I am working on looping over objects within a key:value array in JavaScript to use the string.prototype.replace method for paths to JS files in GulpJS concat tasks. The objective is to generate a list of paths that GULP can utilize, but they re ...

Exploring Vue CLI: Guidelines for updating, deleting, and browsing through all available plugins

After diving into the world of Vue.js, I quickly realized that Vue CLI is essential for speedy development. I got it up and running, created an app, and everything seems to be going smoothly. I decided to enhance my project by adding the Vuetify.js plugin ...

Issue with NodeJS Express's reverse proxy due to an invalid TLS certificate alternative name

I have configured a reverse proxy on my endpoint as shown below: var express = require('express'); var app = express(); var httpProxy = require('http-proxy'); var apiProxy = httpProxy.createProxyServer(); var serverOne = 'https://i ...