How to fill a rect tag inside an SVG with image in Javascript

282 Views Asked by At

I've made several attempts to insert an image inside a rect tag inside an SVG, but none of them worked. What I want is when I click on a button there is a function that changes the fill of the rect. I tried to use snap.svg but it didn't work either. If anyone has any suggestions I would appreciate it.

Code:

HTML:

<button onclick="changeRect('rect252')">Input</a>
<object type="image/svg+xml" id="main" class="edit-area"></object>

Javascript:

let objectTag = document.getElementById('main').setAttribute('data', 'image.svg')

function changeRect(id){
    var obj = document.getElementById("main");
    var svgDoc = obj.contentDocument;
    let svgRect = svgDoc.getElementById(id);
    let pattern = Snap().image('teste.svg', 0, 0, 500, 500).pattern(0, 0, 10, 10);
    svgRect.style.setProperty('fill', pattern)
}

SVG:

<rect
   style="fill:#00000;"
   id="rect252"
   width="51.396542"
   height="31.275505"
   x="120.8588"
   y="92.630028"
   inkscape:label="Right"
   visibility="hidden"/>
0

There are 0 best solutions below