Search code examples
htmlcsssvgbootstrap-5

How can I insert an image in a SVG placeholder?


This is all new stuff to me. I'm trying to use Bootstrap template name "Carousel" as my base. I'm using Bootstrap 5.3.2.

https://getbootstrap.com/docs/5.0/examples/carousel/

All good so far. But i can't find any documentation on how to have my personal rounded image in the SVG placeholder instead of that gray filling.

Any help please? I would like to have an image to replace that gray SVG round placeholder.

<svg class="bd-placeholder-img rounded-circle" width="140" height="140" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: 140x140" preserveAspectRatio="xMidYMid slice" focusable="false">
        <title>Placeholder</title><rect width="100%" height="100%" fill="#777"></rect>
        <text x="50%" y="50%" fill="#777" dy=".3em">140x140</text></svg>

Bootstrap Template screenshot


Solution

  • No need for Bootstrap, wrap it in a native Web Component:

    customElements.define("svg-avatar", class extends HTMLElement {
      connectedCallback() {
        let id   = "id" + crypto.randomUUID();
        let href = "https://octodex.github.com/images/" + this.getAttribute("src");
        this.style.display = "inline-block";
        this.innerHTML     = `<svg viewBox="0 0 100 100">
          <defs>
            <pattern id="${id}" patternUnits="objectBoundingBox" height="100%" width="100%">
              <image href="${href}" width="100" height="100" preserveAspectRatio="xMidYMin slice"/>
            </pattern>
          </defs>
          <circle fill="url(#${id})" cx="50" cy="50" r="49" stroke="black"/>`;
      }
    });
    svg-avatar {
      width: 180px;
      background: rebeccapurple;
    }
    <svg-avatar src="original.jpg"></svg-avatar>
    <svg-avatar src="saint_nictocat.jpg"></svg-avatar>
    <svg-avatar src="grinchtocat.gif"></svg-avatar>