如何使用Javascript动态更改SVG中的图像模式 [英] How to dynamically change the image pattern in SVG using Javascript
本文介绍了如何使用Javascript动态更改SVG中的图像模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用Javascript动态更改/添加图像模式到我页面上的现有SVG?或者任何图书馆。
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);
}
推荐答案
你需要使用setAttributeNS来设置xlink命名空间中的属性,以便
You 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');
应该是
image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'http://www.jampez.co.uk/sensoryuk/events/test.jpg');
这篇关于如何使用Javascript动态更改SVG中的图像模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文