Skip to content
html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    html,
    body {
      width: 100vw;
      height: 100vh;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
  </style>
</head>

<body>
  <canvas id="canvas"></canvas>
  <h3 style="width: 70vw;">
    线段端点样式的默认值是 butt,也就是将端点原样的绘制出来。
    round 是给端点处多画一个半圆,其半径等于线宽(lineWidth)的一半,
    而 square 是给端点处多画一个矩形,其垂直方向长度与线宽一致,水平方向长度等于线宽的一半。
  </h3>

  <script>
    const canvas = document.querySelector('#canvas')
    const context = canvas.getContext('2d')

    canvas.style.background = '#ddd'

    context.lineWidth = 20

    context.beginPath()
    context.moveTo(20, 20)
    context.lineTo(280, 20)
    context.stroke()

    context.lineCap = 'round'
    context.beginPath()
    context.moveTo(20, 60)
    context.lineTo(280, 60)
    context.stroke()

    context.lineCap = 'square'
    context.beginPath()
    context.moveTo(20, 100)
    context.lineTo(280, 100)
    context.stroke()
  </script>
</body>

</html>