繁体   English   中英

用本地图像填充svg元素

[英]Fill svg element with local image

我想填充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)" />

但我无法使用本地图像。

工作小提琴会很棒:)

相关问题:

使用背景图像填充SVG路径元素

在画布中打开本地图像

谢谢!

这似乎适用于最新的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/

你会在这里找到一个不错的例子 它使用最少的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 ,然后设置由onchange事件触发的SVG的xlink:href属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM