Skip to content

画一个三角形

方法一:边框

  • 效果
示例代码
vue
<template>
  <div>
    <div class="triangle"></div>
  </div>
  
</template>
<style scoped>
.triangle {
  width: 0;
  height: 0;
  border-right: 50px solid #00a3af;
  /* 设置宽度为0,所以div的内容为空,才能形成三角形尖角 */
  border-top: 50px solid transparent;
  /* transparent 表示透明 */
  border-bottom: 50px solid transparent;
}
</style>

方法二:旋转

  • 效果
示例代码
vue
<template>
  <div>
    <div class="triangle"></div>
  </div>
</template>
<style scoped lang="scss">
.triangle {
  width: 100px;
  height: 100px;
  border: 0px solid gray;
  position: relative;
  overflow: hidden;

  &::before {
    content: ' ';
    width: 50px;
    height: 50px;
    border: 0px solid red;
    position: absolute;
    background-color: blue;
    transform-origin: top left; // 左上角为原点进行旋转
    transform: rotate(45deg);
  }
}
</style>

方法三:画布绘制

  • 效果
示例代码
vue
<template>
  <canvas ref="canvas" width="200" height="200"></canvas>
</template>

<script setup>
import { onMounted, ref } from 'vue';

const canvas = ref(null);

onMounted(() => {
  drawTriangle();
});

function drawTriangle() {
  const ctx = canvas.value.getContext('2d');

  // 设置起始点
  ctx.beginPath();
  ctx.moveTo(50, 150); // 第一个点
  ctx.lineTo(150, 50); // 第二个点
  ctx.lineTo(50, 50); // 第三个点
  ctx.closePath(); // 闭合路径,形成三角形

  // 设置填充颜色
  ctx.fillStyle = 'blue';
  ctx.fill(); // 填充三角形

  // 设置描边颜色和宽度
  ctx.strokeStyle = 'black';
  ctx.lineWidth = 2;
  ctx.stroke(); // 描边三角形
}
</script>

参考学习

使用CSS画一个三角形