Transform colored svg:image elements into grayscale when clicked upon by utilizing d3

Visit this site

I'm attempting to change all SVG images created using d3.select to grayscale by using the following function:

JavaScript:

<script>

  function convert() {
    d3.selectAll("image")
      .style('filter', 'grayscale(100%)');
  }

</script>

HTML:

<label id="label" style="display:inline;cursor:pointer;" onclick="convert();">
View in Grayscale</label>

The target items I want to affect were generated with:

var images = nodeEnter.append("svg:image")
    .attr("xlink:href",  function(d) { return d.path;})
    .attr("x", function(d) { return -25;})
    .attr("y", function(d) { return -25;})
    .attr("height", 50)
    .attr("width", 50);

While the function in the inspector seems to be correctly adding the filter style attribute for grayscale, the elements themselves are not changing to grayscale.

Any suggestions?

Answer №1

When utilizing SVG images instead of <img> tags, it is important to implement filters as demonstrated in the code snippet below.

var elements = [{
  path: "https://images.pexels.com/photos/459225/pexels-photo-459225.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
  x: 0,
  y: 20
}, {
  path: "https://images.pexels.com/photos/223022/pexels-photo-223022.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
  x: 250,
  y: 20
}];

var elementEnter = d3.select("svg")
  .selectAll("element")
  .data(elements)
  .enter()
  .append("g")
  .attr("transform", function(d) {
    return "translate(" + d.x + "," + d.y + ")";
  });

elementEnter.append("rect")
  .attr("x", 0)
  .attr("y", 0)
  .attr("height", 200)
  .attr("width", 200);

elementEnter.append("svg:image")
  .attr("xlink:href", function(d) {
    return d.path;
  })
  .attr("x", 0)
  .attr("y", 0)
  .attr("height", 200)
  .attr("width", 200);

function applyFilter() {
  d3.selectAll("image")
    .style('filter', 'url(#grayscale)');
}
label {
  position: absolute;
  top: 0;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
<label id="label" style="display:inline;cursor:pointer;" onclick="applyFilter();">
See in Grayscale</label>

<svg x=0 y=0 width=500 height=500>
 <filter id="grayscale">
  <feColorMatrix type="matrix" values="0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0"/>
 </filter>
</svg>

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

Why was the express.js boilerplate code created?

As a newcomer to Node and Express, I am curious about the purpose of the boilerplate directories that are automatically generated when setting up an express project. I have searched online for explanations on the significance of these files without much l ...

Enable the input field once the checkbox has been marked

Here is a checkbox example: <div class="form-group"> <input type="checkbox" id="examination" class="form-control" name="exam" placeholder="Enter Title"> <label>Enable Exam</label> </div> Additionally, I have a disabled inpu ...

Implementing Node.JS ajax to update current JSON information

I am seeking assistance in updating data within a JSON file using NODE.JS. Currently, my method adds the data with the same ID as expected. However, upon receiving the data back, it eliminates the last duplicate because it encounters the old value first. I ...

"Need help on Tumblr: how can I make a div container wrap around a photo

Check out this website. Is there a way to make the div snugly wrap around the image? Currently, it seems to be sticking 4px below the image (as indicated by the red line I added in the background of the div). I'm puzzled as to where those additional ...

Newbie React Developer Struggling to Implement Material-UI Example in React Project, State Functioning Differently from Hooks

I am currently in the early stages of learning React and trying to create a form for a project management web application. For this, I am using material-ui library. I referred to one of the select box component examples from the material-ui documentation ...

Differences between using tables and divs for form layouts

After searching online for examples of form implementations using DIVs, I noticed that most were simple one-column forms. However, my forms are more complex, like the one shown in this image: Although I can easily create these forms using tables, I encoun ...

Employing live labels on a Morris Bar Chart

I'm using the Morris Bar Chart to showcase the sales of different products. To enhance user experience, I want to display dynamic labels when hovering over the bars. The data is being fetched through PHP. array('product' => $row['pr ...

What is causing the failure of these "span" elements within an "a" tag in IE7?

Here is a code snippet that I am working with: HTML (version 4.0) <div class="temperatura"> <a href="/link/" class="temperatura_localita"> <span style="padding-left:12px;"> T ...

Obtain the ID of a YouTube video from an iFrame link using jQuery

Check out this YouTube video: iframe width="560" height="315" src="//www.youtube.com/embed/XbGs_qK2PQA" frameborder="0" allowfullscreen></iframe>` (Hell Yeah! Eminem :P) I only want to extract "XbGs_qK2PQA" from the link provided. Using $(&apo ...

What is the process of transforming async/await code into synchronous code in JavaScript?

Blocking the event loop is generally considered bad practice due to its consequences. However, even the native fs module includes some synchronous functions for specific purposes, such as CLIs using fs.readFileSync. I am interested in converting the follo ...

Conceal the toolbar element if it is not at the top of the page

I am encountering an issue with my toolbar. When I scroll down, the transparent background of the toolbar disappears and it looks like this: . How can I hide this component when the page is scrolled down and show it again when scrolling back up to the top ...

Rails encountered a syntax error while attempting to parse JSON data, due to an unexpected character found at line 2, column 1

I'm a beginner when it comes to using AJAX in Ruby on Rails. What I'm trying to achieve is that when a user clicks on a link with the class .link (redirecting to an external site, for example www.google.de), it should send data - specifically the ...

Is it advisable to approve automatic pull requests initiated by dependabot for updating the yarn.lock file?

I've recently received some pull requests from "dependabot" in a JavaScript library I am working on, like the one found here. While I appreciate the effort to update dependencies to newer versions, it seems strange that each PR only updates the versi ...

Make the inner div fill the entire width within a container of a fixed width

On my blog page, I am currently using the col-md-8 class. Inside this column, my content is displayed. However, I want to stretch a particular div to occupy the full width within the col-md-8. Here is the section of my code: https://i.stack.imgur.com/uPS5 ...

Creating a node.js function that can be used with OracleDB

I'm currently delving into learning nodeJS, but I'm facing a roadblock and can't seem to figure out what's causing the issue. Even the Debugger isn't providing much help. Any assistance or guidance would be greatly appreciated. The ...

Is it possible to use the `new Image()` method in Next.js

Is it possible to use the new Image() function within Next.js? I am encountering an error that states it is not defined. I am aware that I can easily use <Image> inside JSX, but in this particular situation, I am unsure if it will work because I nee ...

event fails to trigger on a fixed positioned element

Here's the code snippet I've been working with: if ($('body.page-service-map').length || $('body.page-contact').length) { $(document.body).append('<div class="black-overlay"></div>'); ...

Using Jquery to iterate through a dynamic list of elements

Currently, I am exploring the idea of creating a forEach loop that can handle an unspecified number of elements. The goal is to randomly select one element, perform XYZ actions on it, make it visible, and then eliminate it from consideration. This process ...

Why isn't the AngularJS injected view resizing to fit the container?

As a novice delving into a project in the MEAN stack, I'm encountering inconsistent HTML previews. When I view it independently versus running it from the project, the display varies. Here's the intended appearance (in standalone preview): imgu ...

Debugging the Force-Directed D3 Graph

I stumbled upon a fantastic article that provided a detailed guide on creating a beautiful D3 force layout graph. However, I'm facing some difficulties with the JSON source: The "links" attribute in the author's JSON doesn't seem clear to m ...