admin管理员组文章数量:1319025
How can I dynamically change/add an image pattern into an existing SVG on my page using Javascript? Or any library.
This is what I've got so far..
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', '.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);
}
How can I dynamically change/add an image pattern into an existing SVG on my page using Javascript? Or any library.
This is what I've got so far..
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);
}
Share
Improve this question
asked Nov 14, 2012 at 12:25
Daniel HillDaniel Hill
1031 silver badge6 bronze badges
1 Answer
Reset to default 9You neeed to use setAttributeNS to set attributes that are in the xlink namespace so
image.setAttribute('xlink:href', 'http://www.jampez.co.uk/sensoryuk/events/test.jpg');
should be
image.setAttributeNS('http://www.w3/1999/xlink', 'xlink:href', 'http://www.jampez.co.uk/sensoryuk/events/test.jpg');
本文标签: How to dynamically change the image pattern in SVG using JavascriptStack Overflow
版权声明:本文标题:How to dynamically change the image pattern in SVG using Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742050297a2418029.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论