canvas 画正方形和圆形

绘制正方形

<!DOCTYPE html>
<html lang="en">
<head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
      <style>
            canvas{
                  background-color: pink;
            }
      </style>
</head>
<body>
      <!-- 画布标签 -->
      <canvas width="600" height="400"></canvas>
      <!-- canvas 是h5新增的画布标签,默认300*150  在IE 6 7 8下都不能用 有兼容性
           cnavas 自身并不具备绘图的功能
           如果在canvas上面进行绘制,需要获取canvas相关的API,通过canvas API进行绘制
           canvas 可以用于 游戏  数据可视化(数据图表)
      -->
      <script>
                  // 绘制正方形
            // 获取canvas标签
            var cs=document.querySelector('canvas')
            // 获取canvas绘图上下文(canvas绘图的相关API)
            var ctx=cs.getContext('2d')
            
            // 绘图
            // 01 移动画笔moveTo(x,y) 坐标
            ctx.moveTo(100,100)
            // 02 划线  坐标
            ctx.lineTo(300,100)
            ctx.lineTo(300,300)
            ctx.lineTo(100,300)
            ctx.lineTo(100,100)
            // 以上两行代码只是一个路径,但还没有绘制
            // 03 绘制
            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">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
      <style>
            canvas{
                  background-color: pink;
            }
      </style>
</head>
<body>
      <canvas width="500"  height="500"></canvas>

<script>
            // <!-- 获取标签 -->
            var cs=document.querySelector('canvas')
            // 获取绘图API
            var ctx=cs.getContext('2d')

            // 绘制园
            // arc(x,y,r,star,end,isNI)
            // x y坐标   r半径     star起始弧度  end终止弧度  isNI是否逆时针
            // 角度和弧度的关系  角度/180=弧度/pI
            // 弧度=角度/180*PI
            ctx.arc(100,100,60,0,360/180*Math.PI)
            ctx.stroke()


</script>
      
</body>
</html>
原文地址:https://www.cnblogs.com/javascript9527/p/11397160.html