【问题标题】:How to dynamically change the image pattern in SVG using Javascript如何使用 Javascript 动态更改 SVG 中的图像模式
【发布时间】:2012-11-02 22:44:33
【问题描述】:

如何使用 Javascript 将图像模式动态更改/添加到页面上的现有 SVG 中?或任何图书馆。

这是我到目前为止所得到的......

function addSvgStuff(svg, id) {

    var svgNS = svg.namespaceURI;
    var pattern = document.createElementNS(svgNS, 'pattern');

    pattern.setAttribute('id', id);
    pattern.setAttribute('patternUnits', 'userSpaceOnUse');
    pattern.setAttribute('width', 500);
    pattern.setAttribute('height', 500);

        var image = document.createElementNS(svgNS, 'image');
        image.setAttribute('xlink:href', 'http://www.jampez.co.uk/sensoryuk/events/test.jpg');
        image.setAttribute('x', -100);
        image.setAttribute('y', -100);
        image.setAttribute('width', 500);
        image.setAttribute('height', 500);

    pattern.appendChild(image);

    var defs = svg.querySelector('defs') ||
    svg.insertBefore( document.createElementNS(svgNS,'defs'), svg.firstChild);

    $('svg polygon').attr('fill', 'url(#' + id + ')');

    return defs.appendChild(pattern);
}

【问题讨论】:

    标签: javascript image svg


    【解决方案1】:

    你需要使用 setAttributeNS 来设置 xlink 命名空间中的属性所以

        image.setAttribute('xlink:href', 'http://www.jampez.co.uk/sensoryuk/events/test.jpg');
    

    应该是

        image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'http://www.jampez.co.uk/sensoryuk/events/test.jpg');
    

    【讨论】:

    • 非常感谢。一直在找这个。
    • @DanielHill jampez.co.uk 是旧的投资组合网站。你到底是从哪里得到这个代码的?
    猜你喜欢
    • 1970-01-01
    • 2013-11-17
    • 2012-04-10
    • 2011-03-11
    • 2015-09-22
    • 1970-01-01
    • 2020-09-27
    • 2012-04-27
    • 2016-05-06
    相关资源
    最近更新 更多