Canvas 画布

183 阅读1分钟

本文通过代码小例子带你走进 Canvas

1、绘制线条

  <!-- 创建画布  -->
<canvas id="canvas" width="800" height="600"></canvas>
<script>
    const canvas = document.querySelector('#canvas')
    // 获得二维绘画对象
    const ctx = canvas.getContext('2d');

    ctx.lineWidth = 3 // 线条宽度
    ctx.fillStyle = 'pink' // 填充色
    ctx.strokeStyle = 'red' // 线条色
    // 线条(绘制三角形)
    ctx.moveTo(100,100) // 起点(x,y)
    ctx.lineTo(200,200) // 下一点(x,y)
    ctx.lineTo(200,300)
    ctx.lineTo(100,100)
    ctx.stroke() // 画线条
    ctx.fill() // 做填充
    
    ctx.beginPath() // 开始新路径
    ctx.moveTo(300,300)
    ctx.lineTo(300,400)
    ctx.lineTo(400,400)
    ctx.closePath() //返回到当前子路径起始点
    ctx.stroke()
    ctx.fill() 
 </script>

2、绘制图形

 <script>
      // 绘制矩形 (起点x,起点y,宽,高)
       ctx.rect(100,150,200,200)
       ctx.stroke()
       ctx.fill()
      // 简写
      ctx.strokeRect(100, 100, 50, 50);
      ctx.fillRect(150, 50, 50, 50);
      // 清除矩形区块(起点x,起点y,宽,高)
      ctx.clearRect(165, 60, 20, 20);

      // 绘制圆形(x,y,半径,圆弧的起始点,圆弧的终点)
      ctx.arc(300, 300, 100, 0, Math.PI * 2);
      ctx.stroke();
      ctx.fill();
  </script>

3、渐变色及文字

   <script>
      const canvas = document.querySelector("#canvas");
      // 获得二维绘画对象
      const ctx = canvas.getContext("2d");

      // 渐变色(起点x,起点y,终点x,终点y)
      const gra = ctx.createLinearGradient(20, 20, 100, 100);
      gra.addColorStop(0, "skyblue");
      gra.addColorStop(0.5, "pink");
      gra.addColorStop(0, "cyan");
      // 创建一个渐变矩形
      ctx.fillStyle = gra;
      ctx.fillRect(20, 20, 100, 100);

      // 文字(文本,起点x,起点y,最大宽度)
      ctx.font = '50px "微软雅黑"';
      ctx.shadowColor = "black"; //阴影颜色
      ctx.shadowBlur = 6;// 模糊程度
      ctx.shadowOffsetX = 10; //阴影水平偏移距离
      ctx.shadowOffsetY = 10; //阴影垂直偏移距离
      ctx.fillText("你好!", 300, 300); // 实心字
      ctx.strokeText("你好!", 400, 400); // 空心字
   </script>

4、画板案例

    <canvas id="canvas" width="800" height="600"></canvas>
  <script>
    const canvas = document.querySelector('#canvas')
    // 获得二维绘画对象
    const ctx = canvas.getContext('2d');

    ctx.lineWidth = 3 // 线条宽度
    ctx.strokeStyle = 'red' // 线条色
    // 标记鼠标状态
    let flag = false 
    // 鼠标按下时触发画
    canvas.onmousedown = function(){
      flag = true
      ctx.beginPath();
    }
    // 鼠标移动时画下路径
    canvas.onmousemove = function(e){
      if(!flag) return
      ctx.lineTo(e.clientX,e.clientY)
      ctx.stroke()
    }
    // 鼠标松开后改变状态
    canvas.onmouseup = function(){
      flag = false
    }
  </script>