Canvas (画一个矩形)

1.视图

<canvas id="myCan" width="500px" height="500px" style="border: 1px solid #3e2e40;"></canvas>
2.JS
<script>
  //拿到 当前canvas 画布节点 
  let canvas = document.getElementById('myCan')
  //做出一个判断 判断是否支持 或者说 一个非空判断
  if (canvas.getContext) {
    //拿起画笔 
    let ctx = canvas.getContext('2d');
    //画出第一个正方形
    //ctx.fillStyle  填充的颜色
    ctx.fillStyle = "#59a387";
    //ctx.fillRect  x,y,width,height
    //x 离left的距离  y 离top的距离
    ctx.fillRect(50,50,100,100);

    //再画一个 带有透明的
    ctx.fillStyle="rgba(43, 56, 77, 0.5)";
    ctx.fillRect(70,70,100,100)

    //让我们擦去刚刚画的
    ctx.clearRect(0, 0, 200, 200)

    //开始画出矩形 
    // 还是先画一个正方形
    ctx.fillRect(25, 25, 100, 100);
     // 利用橡皮搽掉中间不需要的部分
    ctx.clearRect(45, 45, 60, 60);
    // 在画一个正方形边框在中心
    ctx.strokeRect(50, 50, 50, 50);

    // 换个地方画试试看
    ctx.fillRect(300,300,100,100)
    ctx.clearRect(310,310,80,80)
    ctx.strokeRect(320,320,60,60)
  } else {
    alert('没有找到这个画布')
  }
</script>

  

 

 

posted @ 2022-10-11 16:36  热爱前端的5号机器  阅读(113)  评论(0编辑  收藏  举报