Using CSS approach how to set an image to fill a path in SVG?

人走茶凉 提交于 2019-12-04 06:56:49

Here's your thing working - http://jsfiddle.net/eAfTc/

.myClass {
  fill: url(#image);
  stroke: red;
  stroke-width: 5;
}

<svg id='pattern' xmlns="http://www.w3.org/2000/svg" version="1.1">
  <defs>
    <pattern id='image' width="1" height="1" viewBox="0 0 100 100" preserveAspectRatio="none">
      <image xlink:href='http://dummyimage.com/600x400/abc/333' width="100" height="100" preserveAspectRatio="none"></image>
    </pattern>
  </defs>
</svg>
<svg id='triangle' xmlns="http://www.w3.org/2000/svg" version="1.1" width='300px' height='300px'>
    <path d='M0 0 L300 0 L300 300 Z' class='myClass'></path>
</svg>

Note that there's a patternContentUnits and a patternUnits, they do different things. Personally I prefer to use a viewBox for defining the coordinate system.

Here's a new example showing the pattern applied to various elements of different sizes and aspect ratios, it also gets rid of the first svg fragment.

Update: I added 'preserveAspectRatio' to the <pattern> element, and a new example showing the stretching and scaling.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!