lloyd
lloyd

Reputation: 433

Having real images on top of svg

I am working on svg rectangles which represent a farmer's field. Is it possible to have an image of a field on it, just to give it a true sense and view. Here's a sample code of one of the rectangles

<!DOCTYPE html>
 <html>
 <body>

<svg width="400" height="110">
<rect width="300" height="100" style="fill:green; stroke: black; stroke-width:3;" />
</svg>

</body>
</html>

Upvotes: 1

Views: 145

Answers (1)

Alexandr_TT
Alexandr_TT

Reputation: 14585

I used clipPath to cut and place the picture in a rectangle.

<svg width="600" height="200" viewBox="0 0 600 200" > 
<defs>
<clipPath id="field">
 <rect x="25" y="5" width="550" height="190" rx="25" ry="25" style="fill:none; stroke: black; stroke-width:1;" />
 </clipPath>
</defs>
<image xlink:href=" https://i.sstatic.net/MJkK0.jpg" width="600" height="200" clip-path="url(#field)" />
</svg>

If you want to use a different border form instead of a rectangle, for example a circle, then this will be easy to do, replacing the rectangle with a circle in the clipPath.

Option, as suggested by Paulie_D, but it needs a little refinement

If you need a frame around the picture, you will need to add a second transparent rectangle with a border

<rect width="300" height="100" style="fill:none; stroke: black; stroke-width:3;" />

<svg width="400" height="110"> 

<defs>
  <pattern id="field" patternUnits="userSpaceOnUse" width="300" height="100">
    <image xlink:href=" https://i.sstatic.net/MJkK0.jpg" x="-20" y="0" width="350" height="130" />
  </pattern>
</defs>
<rect width="300" height="100"  fill="url(#field)" /> 
<rect width="300" height="100" style="fill:none;  stroke: black; stroke-width:3;" /> 
</svg>

UPDATE

With a black frame looks grim, let's replace it with a shadow.

To create a shadow, the Gauss filter is used, blurring the edges of the bottom rectangle

<filter id="filtershadow" width="120%" height="120%">
      <feGaussianBlur in="SourceAlpha" stdDeviation="4"/> 
</filter>    

<body>  
 <svg width="400" height="110"> 

<defs>

  <filter id="filtershadow" width="120%" height="120%">
      <feGaussianBlur in="SourceAlpha" stdDeviation="4"/> 
</filter>
  <pattern id="field" patternUnits="userSpaceOnUse" width="300" height="100">
    <image xlink:href=" https://i.sstatic.net/MJkK0.jpg" x="0" y="0" width="350" height="130" />
  </pattern>
</defs>
<rect class="rect-shadow" x="10" y="14" width="290" height="90" filter="url(#filtershadow)" style="fill:black; " /> 
 <rect width="300" height="100"  fill="url(#field)" /> 

</svg>

</body>

Upvotes: 2

Related Questions