我正在尝试通过javascript将背景图像设置为svg圈。如果我在<body>
内创建SVG元素,并设置url以填充arrtibute for circle,如下所示。
<script>
function changingImage(e) {
e.currentTarget.setAttributeNS(null, "fill", "url(#img1)");
}
</script>
<body>
<svg height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="white" onmouseover='changingImage(event)'/>
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
<image x="0" y="0" width="100" height="100" xlink:href="http://www.mysolutionzone.com/wp-content/uploads/Download-Nature-Sceneries-photos1.jpg" />
</pattern>
</defs>
</svg>
</body>
但是如果我在javascript中创建所有SVG元素它不起作用。这就是我所拥有的。
<script>
$(document).ready(function () {
var defs = document.createElementNS("http://www.w3.org/2000/svg", "defs");
var pattern = document.createElementNS("http://www.w3.org/2000/svg", "pattern");
pattern.setAttributeNS(null, "id", "img1");
pattern.setAttributeNS(null, "patternUnits", "userSpaceOnUse");
pattern.setAttributeNS(null, "height", "100");
pattern.setAttributeNS(null, "width", "100");
var image = document.createElementNS("http://www.w3.org/2000/svg", "image");
image.setAttributeNS(null, "x", "0");
image.setAttributeNS(null, "y", "0");
image.setAttributeNS(null, "height", "100");
image.setAttributeNS(null, "width", "100");
image.setAttribute("xlink:href", "http://www.mysolutionzone.com/wp-content/uploads/Download-Nature-Sceneries-photos1.jpg");
//var imageElement = $('<defs><pattern id="image1" x="0" y="0" patternUnits="userSpaceOnUse" height="1" width="1"><image x="0" y="0" xlink:href="http://www.mysolutionzone.com/wp-content/uploads/Download-Nature-Sceneries-photos1.jpg"></image></pattern></defs>');
pattern.appendChild(image);
defs.appendChild(pattern);
$('svg').append(defs);
});
function changingImage(e) {
e.currentTarget.setAttributeNS(null, "fill", "url(#img1)");
}
</script>
<body>
<svg height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="white" onmouseover='changingImage(event)'/>
</svg
</body>
还有另一种方法吗?