我想填充一个 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)" />
但我无法让它与本地镜像一起工作。
一个能用的 fiddle 会很棒 :)
相关问题:
Fill SVG path element with a background-image
谢谢!
最佳答案
这似乎适用于最新的 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);
});
最后,一个有效的 fiddle 演示:https://jsfiddle.net/5qLb9m1t/
关于javascript - 用本地镜像填充 svg 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37321736/