Tips for utilizing the "g" element in SVG within CoffeeScript to rotate an object in D3

I'm experimenting with creating a design similar to the following SVG code snippet:

<svg width="12cm" height="4cm" viewBox="0 0 1200 400"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
  <desc>Example rect02 - rounded rectangles</desc>

  <rect x="100" y="100" width="400" height="200" rx="50"
        fill="green" />

  <g transform="translate(700 210) rotate(-30)">
    <rect x="0" y="0" width="400" height="200" rx="50"
          fill="none" stroke="purple" stroke-width="30" />
  </g>
</svg>

I aim to achieve a result like the image below using this CoffeeScript snippet:

canvas = d3.select("body")
    .append("svg")
    .attr("width",2600)
    .attr("height",2600)

rect1 = canvas.append("rect")
    .attr("width",400)
    .attr("height",200)
    .attr("x",100)
    .attr("y",100)
    .attr("rx",50)
    .attr("fill","green")

rect2 = canvas.append("rect")
    .attr("width",400)
    .attr("height",200)
    .attr("x",650)
    .attr("y",50)
    .attr("rx",50)
    .attr("fill","none")
    .attr("stroke-width",30)
    .attr("stroke","Indigo")
    .append("g")
    .attr("transform","translate(700 200) rotate(-30)")

I encountered an issue while trying to rotate the "Indigo" rectangle using the "g" element, resulting in an unexpected output.

If you have any suggestions or tips on working with CoffeeScript and D3, I would greatly appreciate it.

Thank you!

Answer №1

It appears that you are incorrectly inserting the <g> element into the second rectangle instead of the other way around. As a result, the transformation on the <g> element is not affecting the rectangle. To fix this, make sure to first append the <g> to the canvas and then append the <rect> to the <g>:

// ...

rect2 = canvas.append("g")
    .attr("transform","translate(700 200) rotate(-30)")
  .append("rect")
    .attr("width",400)
    .attr("height",200)
    .attr("x",650)
    .attr("y",50)
    .attr("rx",50)
    .attr("fill","none")
    .attr("stroke-width",30)
    .attr("stroke","Indigo")

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 could be causing the href to malfunction on my local website?

I'm currently working on adding a new link that directs to a local HTML website within a menu list on a website. The main website is in ASPX format, but my focus is on the HTML version. The link I want to add leads to an HTML website stored on my loca ...

What steps can be taken to verify if the user has transmitted a JSON Web Token?

Recently started using Express and been struggling with this particular error for quite a while. const token=req.header("jwt") console.log(token) if(!token ){ return res.json('no jwt') console.log('nojw ...

How do I incorporate global typings when adding type definitions to an npm module?

Suppose I create a node module called m. Later on, I decide to enhance it with Typescript typings. Luckily, the module only exports a single function, so the m.d.ts file is as follows: /// <reference path="./typings/globals/node/index.d.ts" /> decl ...

Avoid loading external scripts from third-party sources such as JavaScript libraries, Bing Maps API, and Lighthouse performance tool

Issue: The Bing maps API I incorporated into my assignment is loading unnecessary CSS and scripts, causing a noticeable decrease in my lighthouse scores. Is there a way to prevent third-party code (such as Bing Ads) from loading when fetching the maps for ...

Require assistance with handling Ajax when a function with an Ajax call is repeatedly invoked

I am seeking guidance with ajax as I am still new to it. A problem arises when the same ajax call is made multiple times before the previous one completes its execution, resulting in an empty pop-up on the user interface. How can this issue be resolved? Es ...

Creating Pop-up Dialog Boxes in WebForms Using jQuery

I have implemented a Plugin in Webforms using jQuery UI dialog. Since I have a Content Place holder on my Form, I had to modify the code as shown below: <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> <link rel="stylesheet" ...

Chunk loading in IE 11 has encountered an error

Having an issue with my website which is created using Angular 5. It seems to be malfunctioning in IE 11, and I am encountering the following error in the console: https://i.stack.imgur.com/Ek895.png Any insights on why my Angular code isn't functio ...

JavaScript tip: Improve the way you highlight the current navigation page while scrolling by finding alternative methods to using "scrollY > x"

Currently, my webpage layout is divided into 4 sections - HOME, ABOUT, SKILLS, and CONTACT. Below is the JavaScript code I am using to highlight a specific section on the navigation bar based on the scroll position: let home = document.querySelector(" ...

Learn how to showcase real-time stock information from Yahoo Finance on an Android device. See the JSON format provided below for guidance

finance_charts_json_callback( { "meta" : { "uri" :"/instrument/1.0/PTC/chartdata;type=quote;range=1d/json/", "ticker" : "ptc", "Company-Name" : "PTC Inc.", "Exchange-Name" : "NMS", "unit" : "MIN", "timezone" : "EDT", "curr ...

Next.JS is having trouble importing the URL class from the 'url' module in Node

Recently, while developing with next.js and webpack 5, I encountered an issue where my URL class import stopped working unexpectedly. Upon running npm run build, the following error message appeared: Attempted import error: 'URL' is not export ...

Where the package.json file resides

Is there a designated location for the package.json file in a project, like within the project directory? Where should the package.json file be located in a multi-component project? What is the significance of having version 0.0.0 in th ...

Retrieve the selected options from the checkbox and transfer them to the input text field

In the following example, I am attempting to extract all values of the inputs once they are checked and display them in a text input that will be sent via email. However, I am facing an issue where only the last option is being printed in that input instea ...

The Angular2 Observable fails to be activated by the async pipe

Take a look at this simple code snippet using angular2/rxjs/typescript public rooms: Observable<Room[]>; constructor ( ... ) { this.rooms = this.inspectShipSubject .do(() => console.log('foo')) .switchMap(shi ...

Send the user back to the previous page once authentication is complete

I am integrating Google authentication through Passport in my web application and I am facing an issue with redirecting the user back to the original page they requested after a successful sign-in. It seems like the use of location.reload() might be causin ...

Steps to display the Sidebar on top of the main information page

One unique feature of my website is the FiltersSideBar located on the left side of the page. It contains various filters to refine search results. To optimize user experience, I implemented a function that hides the sidebar at specific browser window size ...

Verify the functionality of a specific method invoked within another method through unit testing

I currently have a method in my Angular application that is triggered upon clicking. Inside this method, I pass a value to another private method. .ts file public onViewItem(item: Results): void { const ids = [item.data['id']]; this.anot ...

What is the best way to add all IDs to an array, except for the very first one

Is there a way to push all response IDs into the idList array, excluding the first ID? Currently, the code below pushes all IDs to the list. How can it be modified to exclude the first ID? const getAllId = async () => { let res = await axios({ m ...

Ways to expand the dimensions of a Popup while including text

I am using a bootstrap modal popup that contains a Treeview control in the body. The issue arises when the node's text width exceeds the popup's width, causing the text to overflow outside of the popup. Is there a way to dynamically adjust the ...

Navigate to all hyperlinks in browser without the use of jQuery - specifically for Firefox OS

I stumbled upon this interesting solution on a programming forum. I'm curious, how does this code work without relying on jquery? $('a[href^=http]').click(function(e){ e.preventDefault(); var activity = new MozActivity({ name: ...

Could someone provide me with guidance on how to troubleshoot this error message?

[0] Unhandled rejection MongoError: (Unauthorized) not authorized on admin to execute command { listIndexes: "sessions", cursor: { } } [0] at MongoError.create (/Users/biggahd/Desktop/Mars-EMS-1/backend/node_modules/mongodb-core/lib/error.j ...