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)

    //擦去刚刚上面画的
    ctx.clearRect(0, 0, 500, 500)
 
    // 然后来画一个三角形
    // 开启一个路径
    ctx.beginPath()
    //x,y   x 代表离left的距离  y代表离Top的距离 它是移动笔触
    ctx.moveTo(75,50)
    // 创建一条 由👆 moveTo 创建的起始距离 画一条多少距离到多少距离的线
    ctx.lineTo(75,200)
    // 接着上面的200的位置 再往离top 25的地方延申一根线 
    ctx.lineTo(200,55)
    //填充刚刚画的区域
    ctx.fill()

    //画出一个笑脸  开启新路径
    ctx.beginPath();
    // 先画一个圆  Math.PI * 2 
    ctx.arc(200, 200, 50, 0, Math.PI * 2, true); // 绘制
    // 把笔移动到圆的嘴巴位置
    ctx.moveTo(235, 200);
    // 画一个半圆  false 顺时针  true 逆时针   Math.PI 半圆
    ctx.arc(200, 200, 35, 0, Math.PI, false);   // 口 (顺时针)
    //移动画笔 到左边眼睛位置
    ctx.moveTo(184, 180);
    // 再画个圆
    ctx.arc(180, 180, 9, 0, Math.PI * 2, true);  // 左眼
    //移动画笔 到右边眼睛位置
    ctx.moveTo(220, 180);
     // 再画个圆
    ctx.arc(215, 180, 9, 0, Math.PI * 2, true);  // 右眼
    // 填充线条
    ctx.stroke();
    // 填充底色
    ctx.fill()
  } else {
    alert('没有找到这个画布')
  }
</script>

  效果 ---------------

 

 

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