实现一个三角形的几种方法

最近面试有被问到如何实现一个三角形,借此机会总结一下,将常用的几种方法梳理一遍。
源文件地址:创建一个三角形

绘制三角形的几种方法汇总

方法1. transform rotateZ(45deg) + 父子divoverflow:hidden

HTML

    <div class='triangle1-wrap'>
        <div class='triangle1'></div>
    </div>

CSS

    .triangle1-wrap{
        width:50px;
        height:50px;
        overflow:hidden;
    }
    .triangle1{
        width:50px;
        height:50px;
        background-color:red;
        transform:rotateZ(45deg);
        margin-top:35px;
    }

方法2. 设置border

HTML

    <div class='triangle2'></div>

CSS

    .triangle2{
        width:0px;
        height:0px;
        border-top:solid 50px red;
        border-bottom:solid 50px transparent;
        border-left:solid 50px transparent;
        border-right:solid 50px transparent;
    }

方法3. canvas

HTMl

    <canvas id='triangle3' width='50' height='50'></canvas>

JS

    const triangle = document.getElementById('triangle3');
    const ctx = triangle.getContext('2d');
    //填充三角形(等边)
    ctx.beginPath();
    ctx.moveTo(50,0);
    ctx.lineTo(0,50);
    ctx.lineTo(50,50); 
    ctx.fillStyle='aqua';
    ctx.fill(); 

方法4. svg

HTML

    <svg class='triangle4'>
        <path name="三角形" fill="green" d="M50 0 L0 50 L50 50  Z"/>
    </svg>

CSS

    .triangle4{
        width:50px;
    }

方法5. 渐变

HTML

    <div class="triangle5"></div>

CSS

    .triangle5{
        width: 50px;
        height:50px;
        background-image:linear-gradient(45deg,#fff 50%, #2980B9 0);
    }

方法6. 伪类

HTML

    <div class="triangle6"></div>

CSS

    .triangle6{
        width:50px;
        height:50px;
        position: relative;
        overflow:hidden;
    }
    .triangle6:after{
        content: "";
        width: 50px;
        height: 50px;
        background-color:brown;
        transform: rotate(45deg);
        position: absolute;
        left: 35px;
        top: 0px;
    }

方法7. background-image

HTML

    <div class="triangle7"></div>

CSS

    .triangle7{
        width:50px;
        height:50px;
        background-image:url('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602140892677&di=754062cafde7897f9550b7691882b17b&imgtype=0&src=http%3A%2F%2Ftrademark-pics-search.oss-cn-shanghai.aliyuncs.com%2Fsmall%2Ft4517751695000576.jpg');
        background-size:100% 100%;
    }

方法8. 字体

HTML

    <div class="triangle8">▲</div>

CSS

    .triangle8{
        font-size:50px;
        color:darkmagenta;
    }

效果展示

posted @ 2020-10-08 12:32  mingL  阅读(1193)  评论(0编辑  收藏  举报