【问题标题】:Replace image element in SVG dynamically动态替换 SVG 中的图像元素
【发布时间】:2012-09-27 20:38:51
【问题描述】:

我想替换 SVG 标记的图像元素。 我希望每次调用一个在 controller.js 中保存图像的对象,我都会获取这个图像并将这个图像表示为 SVG 在名为 default.js 的不同文件中的模糊背景图像。

我该怎么做?

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>  

我想将image id ="backImage" 中的图片替换为其他图片。

Controller.js:

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

【问题讨论】:

    标签: javascript html image svg dom-events


    【解决方案1】:

    尝试使用原生 '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);
    

    它适用于 chrome,我所知道的 =)

    【讨论】:

    • 您不能使用 setAttribute 在 xlink 命名空间中设置属性。如果它在 Chrome 中有效,您应该将其报告为错误。您应该改用 setAttributeNS("w3.org/1999/xlink", "xlink:href", )
    猜你喜欢
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 2020-09-07
    相关资源
    最近更新 更多