一、学习目标

  • 掌握Canvas元素的基本使用方法,包括获取绘图上下文
  • 熟悉2D绘图API的常用方法(矩形、路径、文本绘制)
  • 能够实现简单的图形绘制和动态效果

二、概念讲解

Canvas是HTML5引入的绘图元素,通过JavaScript可以在其上面绘制2D图形、动画、图表等。它提供了一个矩形区域,开发者可以通过调用Canvas API来控制像素级的绘制操作。与SVG不同,Canvas是基于像素的位图绘图,放大后可能失真,但性能更优,适合复杂动画和游戏开发。

核心概念

  • Canvas元素:通过<canvas>标签定义绘图区域,需指定widthheight属性(默认300×150像素)
  • 绘图上下文:通过getContext('2d')获取2D绘图环境,所有绘图操作都通过上下文对象执行
  • 坐标系:默认以左上角为原点(0,0),x轴向右递增,y轴向下递增

三、语法参考

3.1 Canvas元素基本结构

<canvas id="myCanvas" width="500" height="300" style="border: 1px solid #000;"></canvas>

<script>
  // 获取Canvas元素
  const canvas = document.getElementById('myCanvas');
  // 获取2D绘图上下文
  const ctx = canvas.getContext('2d');
  // 开始绘图操作...
</script>

3.2 常用2D绘图API

方法/属性 描述 示例
fillRect(x,y,w,h) 绘制填充矩形 ctx.fillRect(50,50,200,100)
strokeRect(x,y,w,h) 绘制边框矩形 ctx.strokeRect(50,50,200,100)
beginPath() 开始新路径 ctx.beginPath()
arc(x,y,r,start,end) 绘制圆弧/圆形(弧度制) ctx.arc(250,150,80,0,Math.PI*2)
fill() 填充当前路径 ctx.fill()
stroke() 描边当前路径 ctx.stroke()
fillText(text,x,y) 绘制填充文本 ctx.fillText('Hello Canvas', 50, 50)
font 设置文本字体和大小 ctx.font = "24px Arial"
fillStyle 设置填充颜色/渐变/图案 ctx.fillStyle = "#4CAF50"
strokeStyle 设置描边颜色/渐变/图案 ctx.strokeStyle = "red"

四、实战示例

示例1:绘制基本图形组合

<canvas id="shapeCanvas" width="400" height="300" style="border:1px solid #ccc;"></canvas>

<script>
  const canvas = document.getElementById('shapeCanvas');
  const ctx = canvas.getContext('2d');

  // 1. 绘制填充矩形(红色)
  ctx.fillStyle = '#ff4444';
  ctx.fillRect(50, 50, 100, 80);

  // 2. 绘制边框矩形(蓝色,线宽3px)
  ctx.strokeStyle = '#33b5e5';
  ctx.lineWidth = 3;
  ctx.strokeRect(200, 50, 100, 80);

  // 3. 绘制圆形(绿色填充,黄色描边)
  ctx.beginPath();
  ctx.arc(150, 200, 40, 0, Math.PI * 2); // 圆心(150,200),半径40
  ctx.fillStyle = '#00C851';
  ctx.fill();
  ctx.strokeStyle = '#ffeb3b';
  ctx.lineWidth = 2;
  ctx.stroke();

  // 4. 绘制文本(黑色,20px Arial)
  ctx.font = '20px Arial';
  ctx.fillStyle = '#333';
  ctx.fillText('基本图形绘制', 120, 30);
</script>

效果说明:该示例在Canvas上绘制了红色填充矩形、蓝色边框矩形、绿色填充圆形(黄色描边)和标题文本,展示了基本绘图API的组合使用。

示例2:路径绘制与动画效果

<canvas id="animateCanvas" width="400" height="300" style="border:1px solid #ccc;"></canvas>

<script>
  const canvas = document.getElementById('animateCanvas');
  const ctx = canvas.getContext('2d');
  let x = 50; // 圆形初始x坐标
  let speed = 2; // 移动速度

  function draw() {
    // 1. 清除画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 2. 绘制移动的圆形
    ctx.beginPath();
    ctx.arc(x, 150, 30, 0, Math.PI * 2);
    ctx.fillStyle = '#aa66cc';
    ctx.fill();

    // 3. 更新位置(边界检测)
    x += speed;
    if (x > canvas.width - 30 || x < 30) {
      speed = -speed; // 反向移动
    }

    // 4. 循环动画
    requestAnimationFrame(draw);
  }

  // 启动动画
  draw();
</script>

效果说明:该示例实现了一个在Canvas中左右移动的紫色圆形,通过requestAnimationFrame实现平滑动画,每次绘制前清除画布,避免图形重叠。

五、注意事项

  1. Canvas大小设置

    • 必须通过width/height属性设置Canvas尺寸,而非CSS样式(CSS会拉伸画布导致失真)。
    • 示例:<canvas width="500" height="300"></canvas>(正确) vs <canvas style="width:500px;height:300px;"></canvas>(错误)。
  2. 像素精度问题

    • 绘制线条时若出现模糊,可将坐标设置为半像素(如strokeRect(10.5,10.5,80,40)),避免抗锯齿导致的模糊。
  3. 性能优化

    • 复杂动画时使用requestAnimationFrame而非setInterval,确保浏览器刷新率同步。
    • 频繁绘制的场景可使用离屏Canvas缓存静态内容。
  4. 兼容性

    • 所有现代浏览器(Chrome/Firefox/Safari/Edge)均支持Canvas,但IE9及以下不支持,需提供替代内容:
      <canvas>您的浏览器不支持Canvas,请升级浏览器。</canvas>
      

六、自测题

  1. Canvas元素默认的宽高是多少?如何正确设置其尺寸?
  2. 以下代码绘制的图形是什么?ctx.beginPath(); ctx.arc(100,100,50,0,Math.PI); ctx.fill();
  3. 如何在Canvas中实现一个逐渐变色的矩形?(提示:使用线性渐变)
  4. 简述fillRect()strokeRect()的区别,以及它们与rect()+fill()组合的区别。

七、扩展阅读