html - 创建一个透明的内部缺口?

标签 html css svg

我知道如何在外面创建一个凹口,例如:

div:after {
    content: '';
    display: block;
    width: 20px;
    height: 20px;
    -webkit-transform: rotate(45deg);
    transform: rotate(45deg);
}

但我不知道如何仅使用 CSS 来解决这个问题:

enter image description here

槽口必须在容器内部并且必须是透明的。所以上面的解决方案或图像无法解决它。

也许这可以使用 SVG 创建?

编辑

我试过的 is this :

body {
    background: #eee;
}

div {
    position: relative;
    height: 100px;
    width: 200px;
    background: #ccc;
}

div:after {
    content: '';
    position: absolute;
    display: block;
    top: 40px;
    right: -10px;
    width: 20px;
    height: 20px;
    -webkit-transform: rotate(45deg);
    transform: rotate(45deg);
    background: #eee;
}

但这显然不是灵魂,因为伪元素不是透明的。

最佳答案

您不能使用纯 CSS 执行此操作,因为并非所有浏览器都完全支持裁剪(如果交叉兼容性很重要)。

您需要将 SVG 裁剪路径与 CSS 裁剪相结合,最终会得到一个不太优雅的解决方案。

然而,您可以做的是使用 Canvas 创建背景图像。所有支持 HTML5 的主要浏览器都支持 Canvas。使用 canvas 的 backdraw 是你需要做更多的编码来创建形状。可以选择使用图像代替,但使用 Canvas 可以让您保持一切清晰(并且不会像拉伸(stretch)时的图像那样模糊)。

以下解决方案将产生此结果(我添加了红色边框以显示透明区域)。您可以调整参数以使其看起来完全符合您的需要,并使用参数扩展它以定义凹口的大小、透明区域的宽度等。代码会自动采用作为参数给定的元素的大小。

demo preview

要添加一个缺口,只需调用:

addNotch(element);

ONLINE DEMO HERE

代码简单明了,执行速度快:

function addNotch(element) {

    /// some setup
    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d'),

        /// get size of element in pixels
        cs = window.getComputedStyle(element),
        w = parseInt(cs.getPropertyValue('width') || '0', 10),
        h = parseInt(cs.getPropertyValue('height') || '0', 10),

        /// pre-calculate some values
        hh = h * 0.5,
        nw = 20,  /// notch size
        nh = nw * 0.5;

    canvas.width = w;
    canvas.height = h;

    /// draw the main shape        
    ctx.moveTo(0, 0);
    ctx.lineTo(w - nw, 0);
    ctx.lineTo(w - nw, hh - nh);
    ctx.lineTo(w - nw - nh, hh);
    ctx.lineTo(w - nw, hh + nh);
    ctx.lineTo(w - nw, h);
    ctx.lineTo(0, h);
    ctx.closePath();

    ctx.fillStyle = '#7c7058';
    ctx.fill();

    /// draw the white arrow
    ctx.beginPath();
    ctx.lineWidth = 2;
    ctx.strokeStyle = '#eee';
    ctx.moveTo(w - nw - nw * 0.33, hh - nw * 0.75);
    ctx.lineTo(w - nw - nw * 1.1, hh);
    ctx.lineTo(w - nw - nw * 0.33, hh + nw * 0.75);
    ctx.stroke();

    /// convert canvas to image and set background of element
    /// with this image    
    element.style.background = 'url(' + canvas.toDataURL() +
                               ') no-repeat left top';

}

关于html - 创建一个透明的内部缺口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18659926/

相关文章:

html - 拉伸(stretch)元素以适应容器

css - 剪辑路径 SVG 在 Firefox 中不缩放 - 在其他浏览器中工作

html - 由于 CSS 动画,未处理复选框上的单击事件

javascript - 如何使用 jquery 一次交叉淡化一个 div

css - 内容容器重叠菜单?

jquery - 从顶部而不是从底部的 SVG 动画

javascript - 从 Shiny App 调用时如何在 Rmarkdown 中呈现表格和数学

javascript - 悬停时平滑过渡

svg - GraphViz - 将边缘标签链接到另一个点图

html - SVG渐变不起作用