Home >Web Front-end >CSS Tutorial >How to Add an Image to a D3 Circle on Hover Using SVG Patterns?

How to Add an Image to a D3 Circle on Hover Using SVG Patterns?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-24 20:52:13404browse

How to Add an Image to a D3 Circle on Hover Using SVG Patterns?

Adding an Image to a D3 Circle Using Patterns

When attempting to add an image to an existing circle in D3, the image fails to display after hovering, despite the circle rendering and responding to mouseover events when using simple fill attributes.

To resolve this, it is necessary to utilize a pattern in the SVG. The pattern defines the image's positioning and scaling. Here's an example:

<svg>

In D3, you can then modify the circle's fill to use the pattern:

svg.append("circle")
  .attr("class", "logo")
  .attr("cx", 225)
  .attr("cy", 225)
  .attr("r", 20)
  .style("fill", "transparent") // Make the circle transparent to display the image
  .style("stroke", "black")
  .style("stroke-width", 0.25)
  .on("mouseover", function() {
    d3.select(this)
      .style("fill", "url(#image)");
  })
  .on("mouseout", function() {
    d3.select(this)
      .style("fill", "transparent");
  });

This code appends a circle to the SVG and styles its fill to be transparent, allowing the image from the pattern to be visible. Hovering over the circle changes the fill to display the image, while mouseout sets the fill back to transparent.

The above is the detailed content of How to Add an Image to a D3 Circle on Hover Using SVG Patterns?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn