SVG with a background image that is centered

Looking to include a centralized image within an SVG.

This image will act as a user avatar, but my attempts have been unsuccessful so far.

.body {
  width: 100%;
  height: 100%;
  background: #1f1b33;
  padding: 2rem;
}

svg {
width: 120px;
}
<div class="body">
    <svg viewBox="0 0 121.375 125.397">
      <g
        id="blank"
        transform="translate(-1460.94 -927.887)"
      >
        <path
          id="wrapper"
          data-name="Caminho 2257"
          d="M80.617,78.013C67.787,91.6,11.606,90.985-8.689,69.872s-20.527-73.915,0-90.659S66.834-47.3,87.13-26.188,93.447,64.424,80.617,78.013Z"
          transform="translate(1484.938 966.119)"
          fill="#fff"
          opacity="0.2"
        />
        <rect
          id="within"
          data-name="Retângulo 365"
          width="97"
          height="97"
          rx="37"
          transform="translate(1475 945)"
          fill="#fff"
        />
      </g>
    </svg>
  </div

I have attempted to insert an image element within the SVG and reference it as a fill, but the image remains off-center.

Answer №1

I successfully replaced the color white with an image.

.body {
  width: 100%;
  height: 100%;
  background: #1f1b33;
  padding: 2rem;
}

svg {
  width: 120px;
}
<div class="body">
<svg
      xmlns="http://www.w3.org/2000/svg"
      xmlns:xlink="http://www.w3.org/1999/xlink"
      width="121.375"
      height="125.397"
      viewBox="0 0 121.375 125.397"
    >
      <defs>
        <clipPath id="clip-path">
          <rect
            id="Retângulo_365"
            data-name="Retângulo 365"
            width="97"
            height="97"
            rx="37"
            transform="translate(-932 2753)"
            fill="#fff"
          />
        </clipPath>
        <pattern
          id="pattern"
          preserveAspectRatio="xMidYMid slice"
          width="100%"
          height="100%"
          viewBox="0 0 450 450"
        >
          <image
            width="450"
            height="450"
            xlink:href="https://www.espacoluzevida.com.br/wp-content/uploads/2016/05/default-female-avatar.png"
          />
        </pattern>
      </defs>
      <g
        id="profile-image-customized"
        transform="translate(-152.94 -170.887)"
      >
        <path
          id="Caminho_2257"
          data-name="Caminho 2257"
          d="M80.617,78.013C67.787,91.6,11.606,90.985-8.689,69.872s-20.527-73.915,0-90.659S66.834-47.3,87.13-26.188,93.447,64.424,80.617,78.013Z"
          transform="translate(176.938 209.119)"
          fill="#fff"
          opacity="0.2"
        />
        <g
          id="Grupo_de_máscara_7"
          data-name="Grupo de máscara 7"
          transform="translate(1099 -2565)"
          clip-path="url(#clip-path)"
        >
          <path
            id="_32814145-woman-avatar-profile-picture-icon-on-light-gray-background"
            data-name="32814145-woman-avatar-profile-picture-icon-on-light-gray-background"
            d="M0,0H97V97H0Z"
            transform="translate(-932 2753)"
            fill="url(#pattern)"
          />
        </g>
      </g>
    </svg>
</div>

Answer №2

There are multiple ways to insert an image into any SVG shape:

  1. One method is using clipPath
  2. Another option is to use mask
  3. Alternatively, you can use a pattern

When inserting an image using any of these methods, it's important to consider the shape of the template.

For symmetrical shapes, the original image should have the same aspect ratio to fit properly.

For example, if the shape is a circle or regular polygon, images with matching width and height should be chosen.

Using mask

A square image was selected for this example

https://i.sstatic.net/UsGg5.jpg

.body {
  
  padding: 2rem;
  background-color:#1f1b33;
}

svg {
width: 25%;
height:25%;
} 
image {
width:100%;
height:100%;
mask:url(#msk1);
}
<div class="body">
    <svg  viewBox="0 0 121.375 125.397" preserveAspectRatio="xMinYMin meet">
 <defs> 
  <mask id="msk1"> 
    <rect width="100%" height="100%" fill="black" />
   <rect
          id="within"
          data-name="Retângulo 365"
   x="10" y="10"
          width="97"
          height="97"
          rx="37"
          fill="white"
  stroke="#d5d5d5"
  stroke-width="4"
        />
  </mask>
</defs> 
  <rect width="100%" height="100%" fill="#1f1b33" />
      <g
        id="blank"
        transform="translate(-1460.94 -927.887)"
      >
        <path
          id="wrapper"
          data-name="Caminho 2257"
          d="M80.617,78.013C67.787,91.6,11.606,90.985-8.689,69.872s-20.527-73.915,0-90.659S66.834-47.3,87.13-26.188,93.447,64.424,80.617,78.013Z"
          transform="translate(1484.938 966.119)"
          fill="#fff"
          opacity="0.2"
        /> 
</g>
        <rect
          id="within"
          data-name="Retângulo 365"
          x="10" y="10"
  width="97"
          height="97"
          rx="37"
         
          fill="none"
  stroke="black"
  stroke-width="2"
        />
       
   <image xlink:href="https://i.sstatic.net/UsGg5.jpg" x="0" y="0"/>
    </svg>
  </div>

2. Animation of image rotation when hovering

CSS rules are utilized to create a rotation effect on images

#img {
transform-origin:125px 125px;
  -webkit-transition: -webkit-transform 1s ease-in-out;
          transition:         transform 1s ease-in-out;
}

#img:hover {
  -webkit-transform: rotate(360deg);
          transform: rotate(360deg);
}

.body {
  
  padding: 2rem;
  background-color:#1f1b33;
}

svg {
width: 25%;
height:25%;
} 


#img {
width:100%;
height:100%;
mask:url(#msk1);
transform-box: fill-box;
transform-origin:50% 50%;
  -webkit-transition: -webkit-transform 1s ease-in-out;
          transition:         transform 1s ease-in-out;
}

#img:hover {
  -webkit-transform: rotate(360deg);
          transform: rotate(360deg);
}
<div class="body">
    <svg  viewBox="0 0 121.375 125.397" preserveAspectRatio="xMinYMin meet">
 <defs> 
  <mask id="msk1"> 
    <rect width="100%" height="100%" fill="black" />
   <rect
          id="within"
          data-name="Retângulo 365"
   x="10" y="10"
          width="97"
          height="97"
          rx="37"
          fill="white"
  stroke="#d5d5d5"
  stroke-width="4"
        />
  </mask>
</defs> 
 
      <g
        id="blank"
        transform="translate(-1460.94 -927.887)"
      >
        <path
          id="wrapper"
          data-name="Caminho 2257"
          d="M80.617,78.013C67.787,91.6,11.606,90.985-8.689,69.872s-20.527-73.915,0-90.659S66.834-47.3,87.13-26.188,93.447,64.424,80.617,78.013Z"
          transform="translate(1484.938 966.119)"
          fill="#fff"
          opacity="0.2"
        /> 
</g>
               
   <image id="img" xlink:href="https://i.sstatic.net/UsGg5.jpg" x="0" y="0"/>
    </svg>
  </div>

Answer №3

To achieve a seamless pattern fill, it is recommended to use a pattern that matches the aspect ratio of your image. Ensure that the width and height of the pattern align with the dimensions of your rectangle. Setting the patternUnits to userSpaceOnUse is crucial in preventing the pattern from scaling based on the object's bounding box.

.body {
  width: 100%;
  height: 100%;
  background: #1f1b33;
  padding: 2rem;
}

svg {
  width: 120px;
}
<div class="body">
    <svg viewBox="0 0 121.375 125.397">
      <defs>
        <pattern id="patt" patternUnits="userSpaceOnUse" width="97" height="97">
          <image xlink:href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/17496/flace.jpg" width="97" height="97"></image>
        </pattern>
      </defs>
      <g
        id="blank"
        transform="translate(-1460.94 -927.887)"
      >
        <path
          id="wrapper"
          data-name="Caminho 2257"
          d="M80.617,78.013C67.787,91.6,11.606,90.985-8.689,69.872s-20.527-73.915,0-90.659S66.834-47.3,87.13-26.188,93.447,64.424,80.617,78.013Z"
          transform="translate(1484.938 966.119)"
          fill="#fff"
          opacity="0.2"
        />
        <rect
          id="within"
          data-name="Retângulo 365"
          width="97"
          height="97"
          rx="37"
          transform="translate(1475 945)"
          fill="url(#patt)"
        />
      </g>
    </svg>
</div>

Answer №4

According to @Zuber's suggestions in his comments, you can find a detailed explanation on how to achieve this effect here.

Take a look at an example using your code:

.body {
  width: 100%;
  height: 100%;
  background: #1f1b33;
  padding: 2rem;
}

svg { width: 120px; }
<div class="body">
  <svg viewBox="0 0 121.375 125.397">
    <defs>
      <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
        <image xlink:href="https://cdn.pixabay.com/photo/2019/09/14/21/47/dog-4476989_960_720.jpg" x="0" y="0" width="100" height="100" />
      </pattern>
    </defs>
    <g
        id="blank"
        transform="translate(-1460.94 -927.887)"
    >
      <path
          id="wrapper"
          data-name="Caminho 2257"          d="M80.617,78.013C67.787,91.6,11.606,90.985-8.689,69.872s-20.527-73.915,0-90.659S66.834-47.3,87.13-26.188,93.447,64.424,80.617,78.013Z"
          transform="translate(1484.938 966.119)"
          fill="#fff"
          opacity="0.2"
      />
      <rect
          id="within"
          data-name="Retângulo 365"
          width="97"
          height="97"
          rx="37"
          transform="translate(1475 945)"
          fill="url(#img1)"
      />
    </g>
  </svg>
</div>

Answer №5

Why not try utilizing either the pseudo element ::After or ::Before, adjusting it to relative positioning, and then adding a background image while setting your opacity or z-index to your desired value? Just a suggestion to consider.

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

Is it possible to utilize Angular's structural directives within the innerHtml?

Can I insert HTML code with *ngIf and *ngFor directives using the innerHtml property of a DOM element? I'm confused about how Angular handles rendering, so I'm not sure how to accomplish this. I attempted to use Renderer2, but it didn't wor ...

What could be causing the lack of firing with Mobile Safari and jQuery events?

My HTML5/JavaScript app, originally designed for an in-dash car unit, is now being ported to the browser for marketing and presentation purposes. The transition seemed simple at first, just some CSS adjustments for cross-browser compatibility. However, whe ...

Utilizing AngularJS for Your Business Website

We are in the process of developing a new commercial website to replace our current one. Concerns about performance are on our minds. The amount of data we have per page is not very heavy, with a maximum of 150 data binds. We plan to use AngularJS 1.2 t ...

What is the best way to position my content next to my sticky sidebar for optimal visibility?

Just starting out with coding and tackling my initial project using reactJs and bootstrap 5. My aim is to create a sticky side navbar that remains fixed on the side while my content displays next to it, even when navigating through different routes. Unfort ...

Dynamic video autoplay with a hover effect using Bootstrap 3

I am looking to create a hovering effect on an autoloop video similar to what is seen on this website - This specific section of the website demonstrates the effect I am trying to achieve. Prior to hovering, the autoloop video has an overlay displayed on ...

On mobile devices, table rows do not stretch across the full 100% width

I'm facing an issue with a table I'm using for a shopping basket on my website. Everything seems to be working fine until I added a tfoot element, causing the tbody to not span 100% of the container's width. I've been troubleshooting a ...

Storing data in localStorage and serializing it using JSON.stringify and

Currently, I am developing a project that enables users to share memories of places they have visited and also tracks the location and time when the memory was recorded. One hurdle I'm facing involves incorporating localStorage into the application. I ...

The content is not displayed in the d3 visualization

While examining the code of this visualization found at http://bl.ocks.org/mbostock/4062045, I noticed that the name from the JSON file is not displaying alongside the nodes. Even though the code includes: node.append("title").text(function(d) { return ...

Tips for showcasing numerical values using radio buttons

Hello, I am currently working on my project and have a question about calling the ajax function when clicking a button. If(isset($_POST) && ($_POST['GET_PAYMENT'] == '1')) { $totalAmount = $_POST['GET_PAYMENT']; //Total amo ...

Navigate to a fresh web page without encountering any script loading issues

I am currently working on a web application that loads new pages without requiring the browser to reload. While some pages load perfectly fine, others are causing errors due to missing scripts. The code snippet below is used to load a new page: function lo ...

Using AngularJS, you can display repeated elements in a single textarea by utilizing

--> I want to be able to input data into a textarea using just one textarea element. --> The reason for this is so that when the data in MySQL is updated, I can type new data in the textarea while still keeping the existing data. I have tried using ...

A pale tooltip with a light arrow appearing against a soft white backdrop

Can someone help me figure out how to display a white tooltip with a white arrow? I've tried to implement it using the code below, but the white color is not visible against the background. Any suggestions on making it stand out? https://i.sstatic.ne ...

Customizing nvd3 chart colors with CSS: A step-by-step guide

Currently, I am faced with a challenge in SugarCRM as I try to modify the colors of nvd3 charts using CSS. The pie chart colors are structured differently compared to other nvd3 charts, making it difficult for me to figure out how to customize them through ...

access denied on image links

While developing a web app with Angular5, I encountered an issue regarding retrieving image URLs from the 4chan API. Each post in my database contains an image URL, however, when I try to access it through my app, I receive a 403 forbidden error in the con ...

Drawing unusual shapes using canvas arcs in Coffeescript

@.ctx.lineWidth = 20 @.ctx.moveTo(i.x, i.y) @.ctx.arc(i.x, i.y, 3, 0, Math.PI * 2) Can you explain how the code snippet above contributes to the image displayed? ...

Designing a structured layout with div elements resembling tables within a Bootstrap 4 card

I'm struggling with formatting this card. My goal is to create two columns, one with the class col-xs-3 and the other with the class col-xs-9. The titles in the col-xs-3 column should align with the corresponding titles in the col-xs-9 column. Unfort ...

3 Methods for Implementing a Floating Header, Main Content, and Sidebar with Responsive Design

I am following a mobile-first approach with 3 containers that need to be displayed in 3 different layouts as shown in the image below: https://i.sstatic.net/UjKNH.png The closest CSS implementation I have achieved so far is this: HTML: <header>.. ...

When the mouse hovers over the slider, the final image jumps into view

After successfully building an image slider that displays 2 partial images and 1 full image on hover, I encountered a bug when setting the last image to its full width by default. This caused a temporary gap in the slider as the other images were hovered o ...

Learn how to dynamically toggle the visibility of tabs in CodeMirror with a simple button click

Currently, I am developing a Python editor for a website using the Code Mirror JavaScript library. There is a button called toggle invisibles that, when clicked, displays spaces and end-of-line markers. I also wanted to show tabs, which are not supported b ...

Issue with specific selectors causing React CSS module malfunction

Currently, I am a beginner in learning React and have been experimenting with CSS modules. Even though Menu.module.css is mostly functioning correctly, it seems to be having an issue applying styles to the .menu a.last selector for some reason (although i ...