如何创建多边形 div

How to create a polygon shape div

我想创建 HTML 元素,如图片所示:

一个问题是 DIV 元素具有多边形形状而不是常规矩形,将作为弹出窗口之类的东西放置在其他元素之上,并且在该元素内部有必要在源中显示具有矩形形状的图像但是在网络上显示像在左侧填充所有 space 个包含的三角形。

您认为如果不将显示的图像以适当的多边形格式准备为透明 PNG,是否有可能实现这一点?只能通过 CSS3 转换或使用 canvas 或 SVG?

一种方法可能是将图像分成两个容器,大小为父容器的 50%,分别变换每个容器并将背景定位为看起来像一个单一的图像。变换可以是倾斜(在答案中使用)或基于透视的旋转。

请注意,由于我们正在转换容器,因此我们必须对实际图像应用反转效果才能使其看起来正常。

.image {
  position: relative;
  height: 150px;
  width: 450px;
  overflow: hidden;
}
.top-container,
.bottom-container {
  position: absolute;
  left: 0px;
  height: 50%;
  width: 100%;
  overflow: hidden;
  backface-visibility: hidden;
}
.top-container {
  top: 0px;
  transform-origin: right bottom;
  transform: skew(-20deg);
}
.bottom-container {
  bottom: 0px;
  transform-origin: right top;
  transform: skew(20deg);
  background-position: 0% 100%;
}
.top-container:after,
.bottom-container:after {
  position: absolute;
  content: '';
  height: 100%;
  width: 100%;
  left: -14px;  /* tan(20) * (height/2) / 2 */
  background: url(http://lorempixel.com/450/150);
  background-size: 100% 200%;
}
.top-container:after {
  top: 0px;
  transform: skew(20deg);
}
.bottom-container:after {
  bottom: 0px;
  transform: skew(-20deg);
  background-position: 0% 100%;
}

/* Just for demo */

body {
  background: linear-gradient(90deg, crimson, indianred, purple);
}
.image2 {
  margin-top: 10px;
  height: 150px;
  width: 450px;
  background: url(http://lorempixel.com/450/150);
}
<div class="image">
  <div class='top-container'></div>
  <div class='bottom-container'></div>
</div>


<!-- this is the actual image for comparison -->

<h3>Original Image</h3>
<div class='image2'></div>


我正要建议使用 SVG 和 clipPath,但由于 Persijn 已经发布了该示例,我在下面添加了一个不同的版本 polygon

.vector {
  position: relative;
  height: 150px;
  width: 450px;
}
svg {
  position: absolute;
  top: 0px;
  left: 0px;
  height: 100%;
  width: 100%;
}
polygon {
  fill: url(#image);
}

/* Just for demo */

body {
  background: linear-gradient(90deg, crimson, indianred, purple);
}
<div class='vector'>
  <svg viewBox='0 0 450 150' preserveAspectRatio='none'>
    <defs>
      <pattern id='image' height='150' width='450' patternUnits='userSpaceOnUse'>
        <image xlink:href='http://lorempixel.com/450/150' height='150' width='450' />
      </pattern>
    </defs>
    <polygon points='15,0 450,0 450,150 15,150 0,75' />
  </svg>
</div>

SVG

Fiddle example

Jbutler438

找到的解决方案

在 svg 中使用 clip-path 和图像标签,您可以轻松地在前面剪出箭头形状。

<?xml version="1.0" ?>
<svg width="300px" height="300px" viewBox="0 0 100 100" version="1.1" xmlns="http://www.w3.org/2000/svg">

  <defs>
    <clipPath id="myClip">
      <path d="M30 0, 100 0, 100 100, 30 100 0,50Z" />
    </clipPath>
  </defs>

  <image xlink:href="http://lorempixel.com/300/300" x="0" y="0" width="100%" height="100%" clip-path="url(#myClip)" />


</svg>