canvas画矩形

万丈高楼平地起,从零开始,使用 canavas 画矩形的多种方式

<!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>
  </head>
  <style>
    #can {
      border: 1px solid #999;
    }
  </style>
  <body>
    <canvas width="500" height="500" id="can"></canvas>
  </body>
  <script>
    // ctx.beginPath();    开启一个独立作用域(独立的绘制路径)
    // ctx.closePath();    自动连接起点和终点,形成一个封闭区域

    // //  获取画布上下文对象
    const ctx = document.getElementById("can").getContext("2d");

//第一种方式:和画直线一样,从0开始,自己手动输入坐标点
    // 设置起点坐标
    ctx.moveTo(10, 10);
    // 设置第一个拐点坐标
    ctx.lineTo(310, 10);
    // 设置第二个拐点坐标
    ctx.lineTo(310, 102);
    // 设置第三个拐点坐标
    ctx.lineTo(10, 102);
    // 设置颜色
    ctx.strokeStyle = "skyblue";
    // 设置粗细
    ctx.lineWidth = "3";
    // 自动连接起点和终点,形成一个封闭区域
    ctx.closePath();
    ctx.stroke();

// 第二种方式:调用内置的矩形方法
     ctx.rect(10, 10, 300, 300);    
     ctx.stroke();

    // 第三种方式:调用内置的填充矩形方法
    ctx.fillStyle='pink';
    ctx.fillRect(10, 10, 300, 300);
    ctx.strokeStyle='#999';  
    ctx.strokeRect(10, 10, 300, 300);
  </script>
</html>

今天的分享到此结束,欢迎小伙伴们一起交流

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值