Canvas基础篇:线性操作lineWidth详解

前言

在之前的文章中,我们讲解了如何为绘制的图形设置颜色样式以及图形透明度,本篇文章将讲述如何设置图形的线条宽度。

lineWidth

lineWidth:用来设置线条宽度,属性值必须为正数,默认值是 1.0,单位为px。
我们先来看看官方示例:

官方示例

效果预览

简单示例

代码实现

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>官方示例</title>
  </head>
  <body>
    <canvas id="canvas" width="400" height="400"></canvas>
    <script>
      const canvas = document.getElementById('canvas');
      const ctx = canvas.getContext('2d');

      for (let i = 0; i < 10; i++) {
        ctx.lineWidth = 1 + i;
        ctx.beginPath();
        ctx.moveTo(5 + i * 14, 5);
        ctx.lineTo(5 + i * 14, 140);
        ctx.stroke();
      }
    </script>
  </body>
</html>

属性详解

我们再来看一个简单的矩形对比:

效果预览

矩形对比

实现代码

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>矩形对比</title>
  </head>

  <body>
    <canvas id="canvas" width="400" height="400"></canvas>
    <script>
      const canvas = document.getElementById('canvas');
      const ctx = canvas.getContext('2d');
      
      // 第一个矩形 起点横坐标 20
      ctx.beginPath();
      ctx.lineWidth = 10;
      ctx.strokeRect(20, 20, 80, 80);
      ctx.closePath();

      // 第二个矩形 起点横坐标 20
      ctx.beginPath();
      ctx.lineWidth = 1;
      ctx.strokeRect(20, 140, 80, 80);
      ctx.closePath();
      
      // 第三个矩形 起点横坐标 25
      ctx.beginPath();
      ctx.lineWidth = 10;
      ctx.strokeRect(25, 260, 80, 80);
      ctx.closePath();

      ctx.lineWidth = 1;
      ctx.strokeStyle = 'red';
      ctx.setLineDash([10, 5])
      ctx.beginPath();
      ctx.moveTo(20, 0);
      ctx.lineTo(20, 360);
      ctx.stroke();

      ctx.beginPath();
      ctx.lineWidth = 1;
      ctx.strokeStyle = 'red';
      ctx.moveTo(100, 0);
      ctx.lineTo(100, 360);
      ctx.stroke();
    </script>
  </body>
</html>

分析

上述代码中,一共绘制了三个矩形,三个矩形大小相同,但边框宽度不同。从图中我们可以看到:

  1. 第一个矩形和第三个矩形的实际起点发生了偏移;
  2. 第三个矩形的宽度正好比第一个矩形的宽度多了一个lineWidth的宽度:10px。

结论

  1. 使用lineWidth绘制矩形时,矩形的实际宽度为:lineWidth+width,矩形的实际高度为:lineWidth+height,矩阵的实际起始坐标为(x - lineWidth / 2, y - lineWidth / 2)
  2. 同理,当使用lineWidth绘制曲线时,如arc()方法,曲线的实际半径为lineWidth + radius

结语

本文主要介绍了如何给图形设置线条宽度,对于文章中错误的地方或者有任何问题,欢迎在评论区留言分享!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值