Replace image element in SVG dynamically

2020-07-27 09:32发布

问题:

I would like to replace an image element of SVG tag. I want that every call to an object which holds the image in controller.js, I will take this image and represent this image as a blur background image by SVG in different file called default.js.

How should I do it?

default.html :

<div id="backgroundImage">
        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
            <defs>
                <filter id="myGaussianBlur" x="0" y="0">
                    <feGaussianBlur in="SourceGraphic" stdDeviation="2"></feGaussianBlur>
                </filter>
            </defs>
            <image id="backImage" xlink:href="surf.jpg" width="100%" height="100%" preserveAspectRatio="none" filter="url(#myGaussianBlur)" />
        </svg>
    </div>  

I would like to replace the image in image id ="backImage" in other image.

Controller.js:

function setObject(element, value) {
    var id = value.id;
    var image = value.image;
    ????
}

回答1:

Try making use of native 'setAttribute'.

var im = document.getElementById('backImage');
im.setAttribute('xlink:href',"http://sphotos-b.ak.fbcdn.net/hphotos-ak-ash3/s480x480/525959_10151097048652029_155651648_n.jpg");
// or mby more correct approach:
//    im.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "http://sphotos-b.ak.fbcdn.net/hphotos-ak-ash3/s480x480/525959_10151097048652029_155651648_n.jpg");
im.setAttribute('width', X);
im.setAttribute('height', Y);

It works in chrome, all i know =)