首页 > 解决方案 > 如何裁剪图像宽度 svg?

问题描述

如何在此 svg 中裁剪带有路径的图像?

<svg width="1440" height="568" viewBox="0 0 1440 568" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0 0H1440V481.821L720 568L0 481.821V0Z" fill="url(#paint0_linear)"/>
<defs>
<linearGradient id="paint0_linear" x1="720" y1="607.026" x2="720" y2="35.2649" gradientUnits="userSpaceOnUse">
<stop stop-color="white" stop-opacity="0"/>
<stop offset="1" stop-color="#0997FF" stop-opacity="0.56"/>
</linearGradient>
</defs>
</svg>

我想在图像上设置 svg 的线性渐变,图像底部的额外空间与主体的背景颜色(深蓝色)相同:

<div class="bg"></div>


.bg {
  width: 100vw;
  min-height: 500px;
  background: url("../assets/images/mySvg.svg"),
     url("../assets/images/myImage.jpg");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}

我有的:

我想要的是:

标签: csssvg

解决方案


将图像放入 SVG。

  • 将图像和渐变组合成一个 SVG 组 ( <g>)
  • <clipPath>然后使用原始路径定义的 SVG 剪辑该组。
  • 将 SVG 放入<div>

body {
  background-color: linen;
}

.bg {
  width: 100vw;
  min-height: 500px;
}
<div class="bg">
  <svg width="100%" viewBox="0 0 1440 568">
    <defs>
      <clipPath id="clip">
        <path d="M0 0H1440V481.821L720 568L0 481.821V0Z"/>
      </clipPath>

      <linearGradient id="paint0_linear" x1="720" y1="607.026" x2="720" y2="35.2649" gradientUnits="userSpaceOnUse">
        <stop stop-color="white" stop-opacity="0"/>
        <stop offset="1" stop-color="#0997FF" stop-opacity="0.56"/>
      </linearGradient>
    </defs>
    
    <g clip-path="url(#clip)">
      <image xlink:href="http://placekitten.com/1440/568" width="1440" height="568"/>
      <rect width="1440" height="568" fill="url(#paint0_linear)"/>
    </g>
  </svg>

  <p>More content here.</p>
</div>


推荐阅读