How do I combine Dj3 rotation?

How do I incorporate rotation into this code snippet:

<html>

<head>
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c8acfb88fbe6fde6fb">[email protected]</a>" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
</head>

<body>
  <script>
    var w = 300,
      h = 300,
      data = [{
          t: "Now",
          v: 50
        },{
          t: "is",
          v: 25
        },{
          t: "the",
          v: 10
        },{
          t: "winter",
          v: 30
        }];

    var svg = d3.select('body')
      .append('svg')
      .attr('width', w)
      .attr('height', h);

    var yScale = d3.scale.linear()
      .range([0, h])
      .domain([60, 0]);

    var label = svg.selectAll("text")
      .data(data)
      .enter()
      .append("text")
      .text(function(d) {
        return d.t;
      })
      .attr("transform", function(d,i){
        var xText = i * (w / data.length);
        var yText = h - yScale(d.v);
        return "translate(" + xText + "," + yText + ") rotate(90)";
      })
      .attr("fill", "black")
      .attr("font-family", "sans-serif")
      .attr("font-size", "11px");
  </script>
</body>

</html>

Using the following code instead:

  <!DOCTYPE html>
    <html>
      <head>
        <title></title>
  <script src="http://d3js.org/d3.v2.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

        <style type="text/css">

        #canvas {
            width: 300px;
            height: 300px;
            background-color: red;
        }

        </style>
      </head>
      <body>
        <div id="canvas" style="border:solid"></div>
        <script type="text/javascript">
    var w = 300,
      h = 300;

    var data = {
      name: "root",
      children: [{
          name: '1',
          size: 70
        },
        {
          name: '2',
          size: 70
        },
        {
          name: '3',
          size: 70
        },
        {
          name: '4',
          size: 70
        },
        {
          name: '5',
          size: 70
        },
        {
          name: '6',
          size: 70
        },
        {
          name: '7',
          size: 70
        },
      ]
    }

        jQuery.fn.rotate = function(degrees) {
        $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                     '-moz-transform' : 'rotate('+ degrees +'deg)',
                     '-ms-transform' : 'rotate('+ degrees +'deg)',
                     'transform' : 'rotate('+ degrees +'deg)'});
        return $(this);
        var r = getRandomInt(0, 180);
    };


    var canvas = d3.select("#canvas")
      .append("svg:svg")
      .attr('width', w)
      .attr('height', h);

    var nodes = d3.layout.pack()
      .value(function(d) {
        return d.size;
      })
      .size([w, h])
      .nodes(data);

    nodes.shift();

    var yScale = d3.scale.linear()
       .range([0, h])
       .domain([60, 0]);

    canvas.selectAll('circles')
      .data(nodes)
      .enter().append('svg:circle')
      .attr('cx', function(d) {
        return d.x;
      })
      .attr('cy', function(d) {
        return d.y;
      })
      .attr('r', function(d) {
        return d.r;
      })
      .attr('fill', 'white')
      .attr('x', 0)
      .attr('y', 0)
      .attr('width', 6)
      .attr('height', 6);

    canvas.selectAll("text")
      .data(nodes)
      .enter()
      .append("text")
      .attr("x", function(d) {
        return d.x;
      })
      .attr("y", function(d) {
        return d.y;
      })
      .text(function(d) {
        return "Pomidorek";
      })
      .attr("text-anchor", "middle")
      .attr("font-family", "sans-serif")
      .attr("font-size", "18px")
      .attr("color", "black")
      .attr("transform", function(d,i){
            var xText = i * (w / children.length);
            var yText = h - yScale(d.size);
            return "translate(" + xText + "," + yText + ") rotate(505)";
          })

        </script>
      </body>
    </html>

I have been attempting to implement this but it seems to be not functioning as expected. This is crucial for me and I'm struggling to identify where I might have gone wrong. The first code successfully rotates text without any issues, whereas in the second code, I am uncertain about how to achieve the same effect.

Answer №1

Upon conducting a quick analysis, I identified an issue in your code:

  .attr("transform", function(d,i){
        var xText = i * (w / children.length); \\the error lies here: perhaps it should be data.children.length
        var yText = h - yScale(d.size);
        return "translate(" + xText + "," + yText + ") rotate(505)";
      })

After implementing the changes, you will notice a rotation effect; however, some text may extend beyond the canvas boundaries.

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

Incorporate validation features within a jQuery method

I am struggling with some HTML and jQuery code that generates links based on user input. HTML <input type="text" id="text" placeholder="Enter text" autofocus /> <a id="link1" class="btn btn-info" href="#" target="_blank"> Search 1 </a> ...

What steps can be taken to resolve the "npm ERR! code ELIFECYCLE" error in a React application?

After attempting to start my React app with npm start, an error occurred : $ npm start > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f3b3d2a212b3c0f7f617e617f">[email protected]</a> start C:\Users&bso ...

Is it possible to utilize an if statement to select a specific Bootstrap modal?

How can I make a modal appear when the user clicks select? The first page has radio buttons (e.g. oneway, twoway), and I want the second page to display different fields based on which radio button is selected. Can I use an if statement for this? If so, ...

Difficulty encountered when loading JSON data using the getJSON function

When I open the JSON file in my web browser and input this code into the console: var p = document.getElementsByTagName('pre'); for(i=0; i < p.length; i++) { var data = JSON.parse(p[i].innerHTML); var pc = data.postalcodes; for (va ...

How can I access and retrieve a local variable using geolocation in HTML5 and the Google Maps API?

Seeking assistance with a coding dilemma: I need to retrieve the geolocation position for use in my calcRoute function. The goal is to set the geolocation as the starting point. Below is the code snippet: function calcRoute(){ var pos; navigator.g ...

Utilizing modal functionality for seamless integration of new data into mui-datatable

When trying to add a new data entry using a modal box, I encountered an issue where the new data was not being added to the datatable. Is there a solution for this problem? Below is the code snippet I used: let id = 0; function createData(name, provider) ...

Issue with ng-disabled not functioning properly for href tag within list item

Is there a way to prevent clicking on the <a> tag within a list item in a UI list so that the associated <div> is not displayed when clicked (excluding the last list item)? I have attempted using ng-disabled directly on the list item attribute ...

Error caused by external Javascript and CSS files blocking the rendering process

Having encountered an issue, I find myself grappling with numerous external blocking rendering errors, as evident from this report: https://developers.google.com/speed/pagespeed/insights/?url=antsmarching.com.au&tab=desktop I put forth my best efforts ...

Monitoring changes in input can be a crucial step in any data analysis

Is there a way to track changes in input using backbone? How it can be achieved in AngularJs: <div ng-controller="W3"> <input type="text" ng-model="val" > <p>{{val}}</p> </div> I would like the value of the in ...

Store a JSON object without creating a reference to it

My issue is presented in a much simpler manner. Here is the json (you can view it here if you wish) {"resource":[{"id":"1408694994","obj":[{"id":"1","action":[{"name":"ON","id":"301"},{"name":"OFF","id":"302"}]},{"id":"2","action":[{"name":"ON","id":"303 ...

Error: Unable to access the 'login' property of an undefined object

An error occurred: Uncaught TypeError: Cannot read property 'login' of undefined........... import Login from '../components/Login.jsx'; import { useDeps, composeWithTracker, composeAll } from 'mantra-core'; export const com ...

The Jquery Ajax .load() function is not working properly

<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery UI Tabs - Expanding content</title> <link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> < ...

How can the value of a number in Angular be changed without altering its original value?

Imagine having the initial number 100. If I enter 50 in another input, it should add 50 to 100. However, if I then change the value from 50 to 80, the total should be 180 and not 230. The goal is always to add numbers to the original sum, not the new valu ...

Deciphering the $resource factory along with the @ symbol prefix

Under this particular service: vdgServices.factory('UserService', ['$resource', function($resource) { return $resource('api/users/:id', {}, { doGet: { method: 'GET', params: { i ...

How to handle multiple formData input in NestJS controller

How can I create a controller in Nest.js that accepts two form-data inputs? Here is my Angular service code: public importSchema(file: File, importConfig: PreviewImportConfig): Observable<HttpEvent<SchemaParseResponse>> { const formData = ...

The 'checked' property cannot be bound to 'mat-button-toggle' as it is not recognized as a valid property in Angular 9

I am encountering an issue with my Angular 9 application. I have integrated angular-material and imported the MatCheckboxModule correctly in the module. Here is the version of the material package I am using: "@angular/material": "^10.2.0&q ...

"Is there a way to retrieve the CSS of all elements on a webpage by providing a URL using

Currently, I am in the process of creating a script that can crawl through all links provided with a site's URL and verify if the font used on each page is helvetica. Below is the code snippet I have put together (partially obtained online). var requ ...

Discovering the Browser Refresh and Close Events in Angular JS: A Comprehensive Guide

Hello, I've attempted using the event below to detect something, but occasionally it doesn't trigger when closing the tab or browser. $window.addEventListener('beforeunload', function(event) { // Your code here }); ...

Retrieving various sets of JSON objects arrays

I have successfully stored an array of JSON objects in the database using the following code: function send_custom_markers() { var reponse = confirm("Send markers to selected contacts?"); if (reponse === true) { var json_markers = new ...

What could be causing the issue with loading data into my MongoDB collection?

Here is the content from my mongo database: https://i.sstatic.net/Z5PVv.png When I use app.post to insert the data, after submitting I can see the object with the dates in the console.log. However, when I try to use create function, it only displays "nul ...