Learn how to instantiate a d3 SVG element using an embedded external SVG file and apply transformations to it

The embedded svg document is sourced from a file.

This is the content of the svg-file:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->

<svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   width="64px"
   height="64px"
   id="svgPic"
   version="1.1"
   inkscape:version="0.48.4 r9939"
   sodipodi:docname="New document 18">
  <g
     id="curvLayer"
     inkscape:label="Curv"
     inkscape:groupmode="layer">
    <path
       style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
       d="M 2.0162099,44.937652 C 19.928085,44.362124 23.033712,29.671999 33.839655,29.657316 44.913406,29.332988 44.178722,15.232728 60.486296,15.244392"
       id="path4373"
       inkscape:connector-curvature="0"
       sodipodi:nodetypes="ccc" />
  </g>
</svg>

Below you can find some HTML and JavaScript code where an attempt is made to manipulate the svg using d3 library, however without success.

<body>
  <embed src="berg4.svg" type="image/svg+xml" id="svgpic"/>

  <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>

  <script type="text/javascript" charset="utf-8">

     var subdoc = document.getElementById("svgPic").getSVGDocument();
     var curvLayer = subdoc.getElementById("curvLayer");
     var myPoint = d3.select("#curvLayer").append("svg:circle")
            .attr("cx", x) //e.g. x = 100
            .attr("cy", y) //e.g. y = 100
            .attr("r", 4.5);
  </script>
</body>

The main question posed here is how to introduce a new element such as a circle into this svg?

Answer №1

Upon reviewing your code, I have identified two main issues:

  1. Element Selection: The use of both document.getElementByID and D3.select is unnecessary. You can simply select the element using D3 with CSS selectors like so:

    d3.select("#curvLayer")
    
  2. Attributes for Circle Elements: The attributes cx and cy for your circles are being set to undefined values 'x' and 'y'. Prior to this, make sure to define these values or set them as static values:

    .append("circle")
        .attr("cx", 10)
        .attr("cy", 10)
        .attr("r", 4.5);
    

To see the updated version with these fixes, check out the jsfiddle link here: http://jsfiddle.net/qAHC2/308/

Answer №2

To successfully integrate D3 with an external SVG file, you must provide D3 with the root element of the SVG. In order to achieve this, you can follow this approach for your specific scenario:

var svgRoot = document.getElementById('svgpic').getSVGDocument().documentElement;
d3.select(svgRoot).select("#curvLayer").append("circle")
                                           .attr("cx", 10)
                                           .attr("cy", 10)
                                           .attr("r", 4.5);

In cases where you are working in Firefox, it might be necessary to utilize contentDocument instead of getSVGDocument().

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

Tips for obtaining the dimensions of a window using bootstrap

While using bootstrap, there is a fixed top navigation bar and a fixed bottom navigation bar in place. I am looking to display a large image in the background that spans the space between these two nav bars and also covers the full width of the window. H ...

How can MongoDB be used to query nested JSON structures?

My JSON data structure is as follows: "marks":{ "sem1" :{ "mark1":10, "total":100 }, "sem2":{ "mark2":20, "total":200 }, "sem3":{ "mark2":30, "total":300 } } I want to display the re ...

ReactJS form submissions failing to detect empty input values

My goal is to use react to console.log the input value. Below is the code I've created: import React from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component{ constructor() { super(); this.proce ...

How can we use THREE.js to make objects track other objects?

Currently, I am in the process of developing the PONG Game and I encountered an issue with making the computer play against the player. My goal is to have the computer follow the y-axis position of the ball, ensuring that both entities have distinct moveme ...

Secure Routes with Moralis for React Router v6 - A Powerful Combination

I'm having trouble figuring out why this piece of code isn't functioning as expected. The variable "isAuthenticated" comes from the Moralis API and is a boolean value. Ideally, if it's true, it should display the "Outlet", and if it's f ...

Transforming JSON/XML into a hierarchical display

I've come across the following XML file: <Person attribute1="value1" attribute2="value2"> value3 <Address street="value4" city="value5">value6</Address> <Phone number="value7" type="value8">value9</Phone> </Pers ...

Personalized search feature for Bootstrap tables

Below is the table structure: <table> <tr> <th>Number</th> <th>Name</th> </tr> <tr> <td>200.10.1234</td> <td>Maria Anders</td> </tr> <tr> < ...

The side navigation panel transition is stuck and failing to slide out as intended

My element is able to slide in smoothly, but encounters trouble when attempting to slide back out. I suspect the issue lies within the syntax for "display: none". Any assistance or recommendations would be greatly appreciated, and feel free to request more ...

The getElementsByTagName function in Javascript may return an empty list for certain tags while functioning properly for others

I am struggling to understand why the method getElementsByTagName is returning an empty list for certain tags. To illustrate this, consider the following example: <!DOCTYPE html> <html> <head> <title>Title</title> ...

The for loop seems to be malfunctioning when placed within the append function

I am facing an issue where I need to wrap the entire content into a single div so that it can be used within a loop inside the append function in JavaScript. However, after wrapping the content in a div, nothing is being displayed. Below is the code snipp ...

Using radio buttons to alter CSS properties of a submit button

I’m struggling to figure out how to change the css class of a submit button when toggling between two radio buttons. I've searched for examples but haven't found one that fits my needs. Can anyone offer some assistance? Below is my form: < ...

Mongoose exploring the use of promises to manage pre-save errors

I'm facing an issue with using pre-save to handle errors for existing users or emails. When I remove the pre-save block, everything works fine, but I get the default mongoose error for duplicates due to using the Unique feature in my schema. I want t ...

Issue with hide.bs.modal event not triggering in Bootstrap 3.2 when using Django 1.6.5 with remote modal content

I need help with a dashboard I'm working on that displays a list of hosts. When a user clicks on a host, I want to show additional details in a modal dialog. Right now, I am using Bootstrap's remote modal feature to trigger a Django view and popu ...

jQuery SlideUp and SlideDown causing Margin Bug in Internet Explorer 7

When clicking the "more info" or "less info" buttons to slide content up or down, a spacing glitch is created in IE7. Using show/hide instead of slideUp/slideDown seems to solve the issue. Is there a way to make sliding work in IE7 without causing this pro ...

Incorporating Multiple Slots for Content Transclusion in Angular 6

In my quest to implement a component with multi-slot transclusion in Angular 6, I came across a valuable resource on this blog post (originally written for Angular 2). The initial step involved creating a component: import { Component, OnInit } from &apos ...

Is Selenium suitable for testing single page JavaScript applications?

As a newcomer to UI testing, I'm wondering if Selenium is capable of handling UI testing for single-page JavaScript applications. These apps involve async AJAX/Web Socket requests and have already been tested on the service end points, but now I need ...

Is it recommended to exclude the NGXS NgxsLoggerPluginModule for production deployments?

When developing, it's common to use the following imports: import { NgxsReduxDevtoolsPluginModule } from '@ngxs/devtools-plugin'; import { NgxsLoggerPluginModule } from '@ngxs/logger-plugin'; Is it recommended to remove these imp ...

jQuery Scrolling Page Issue Not Resolved

I am diving into the world of JavaScript and attempting to develop a simple program that smoothly scrolls to a specific div when a navigation item is clicked. Unfortunately, my code is not functioning as expected and I am struggling to identify the root ca ...

Adding a custom script with wp_enqueue_script() upon form submission: Steps and guidelines

Currently, I'm working on a WordPress plugin that allows users to input inline scripts in a text-area on the plugin settings page, and then save it. My goal is to grab the submitted script and enqueue it in the header/footer of the theme. I've ...

How can Vuetify components be imported separately in the right way?

I’m currently getting acquainted with Vuetify and I’m finding it quite challenging to figure out how to import a specific component for use. My current version of Vuetify is 2.4.2 According to the documentation, they mentioned about the path to vueti ...