Replace image element in SVG dynamically

随声附和 提交于 2019-12-22 00:47:43

问题


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 =)



来源:https://stackoverflow.com/questions/12767436/replace-image-element-in-svg-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!