我想填写一个svg元素,例如带有图像的circle
元素,用户可以通过<input type='file'/>
输入从本地计算机中选择该图像。
我知道您可以使用模式填充svg元素:
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
<image xlink:href="wall.jpg" x="0" y="0" width="100" height="100" />
</pattern>
</defs>
<circle cx=100 cy=100 r=100 fill="url(#img1)" />
但我无法使用本地图像。
工作小提琴会很棒:)
相关问题:
Fill SVG path element with a background-image
谢谢!
答案 0 :(得分:2)
这似乎适用于最新的Chrome和Firefox。
首先,HTML部分:
<input id="upload" type="file"/>
<svg>
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
<image xlink:href="wall.jpg" x="0" y="0" width="100" height="100" />
</pattern>
</defs>
<circle cx=100 cy=100 r=100 fill="url(#img1)" />
</svg>
接下来,JS部分:
var upload = document.getElementById('upload');
var patternImage = document.querySelector('#img1 image');
var currentBlobData = null;
upload.addEventListener('change', function (e) {
var file = this.files[0];
if (currentBlobData) {
URL.revokeObjectURL(currentBlobData);
}
currentBlobData = URL.createObjectURL(file);
patternImage.setAttribute('xlink:href', currentBlobData);
});
最后,一个工作小提琴演示:https://jsfiddle.net/5qLb9m1t/
答案 1 :(得分:-1)
你会发现a decent example here。它使用最少的JavaScript来更新pattern
。根据您给定的代码,结果可能如下所示:
<html>
<head>
<script>
var E;
function prepare(){ E=document.getElementById('imgPath'); }
function change(v){ E.setAttribute("xlink:href", v); }
</script>
</head>
<body onload="prepare()">
<table border="2">
<tr><td><input type="file" formmethod="GET" onchange="change(this.value)" /></td></tr>
<tr><td>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid" width="320" height="286" viewBox="0 0 320 86">
<defs>
<pattern id="imgPattern" patternUnits="userSpaceOnUse" width="100" height="100">
<image id="imgPath" xlink:href="wall2.jpg" x="0" y="0" width="100" height="100" />
</pattern>
</defs>
<circle cx=100 cy=100 r=100 fill="url(#imgPattern)" />
</svg>
</td></tr>
</table>
</body>
</html>
它只使用JavaScript获取图像路径的id
,然后设置由xlink:href
事件触发的SVG的onchange
属性。