跳转到内容

JavaScript Canvas基础

来自代码酷

JavaScript Canvas基础[编辑 | 编辑源代码]

JavaScript Canvas基础是使用HTML5的<canvas>元素进行2D图形绘制的核心技术,它是实现数据可视化、游戏开发、动态UI等功能的底层基础。本章将逐步介绍Canvas的基本用法、绘图API及实际应用场景。

简介[编辑 | 编辑源代码]

<canvas>是HTML5提供的绘图区域,通过JavaScript脚本可以动态绘制图形、图表、图像或动画。它不包含内置的绘图能力,而是通过CanvasRenderingContext2D API提供路径、形状、文本、图像操作等方法。

基本用法[编辑 | 编辑源代码]

创建Canvas元素[编辑 | 编辑源代码]

首先需要在HTML中定义一个<canvas>元素,并设置其宽度和高度:

<canvas id="myCanvas" width="400" height="300"></canvas>

获取绘图上下文[编辑 | 编辑源代码]

通过JavaScript获取2D渲染上下文:

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

绘制基础图形[编辑 | 编辑源代码]

矩形[编辑 | 编辑源代码]

Canvas提供三种矩形绘制方法:

  • fillRect(x, y, width, height):填充矩形
  • strokeRect(x, y, width, height):描边矩形
  • clearRect(x, y, width, height):清除矩形区域

示例:

ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 100, 80);

ctx.strokeStyle = 'red';
ctx.lineWidth = 3;
ctx.strokeRect(200, 50, 100, 80);

输出效果:

  • 蓝色填充矩形(位置:50,50;尺寸:100×80)
  • 红色边框矩形(位置:200,50;尺寸:100×80)

路径[编辑 | 编辑源代码]

路径用于绘制复杂形状,基本步骤: 1. beginPath():开始新路径 2. 绘制命令(如moveTo, lineTo) 3. closePath()(可选) 4. stroke()fill()

示例(绘制三角形):

ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(150, 50);
ctx.lineTo(200, 100);
ctx.closePath();
ctx.stroke();

样式与颜色[编辑 | 编辑源代码]

颜色设置[编辑 | 编辑源代码]

  • fillStyle:填充颜色
  • strokeStyle:描边颜色

支持格式:

  • 颜色名称('red'
  • 十六进制('#FF0000'
  • RGB/RGBA('rgb(255,0,0)'

线型[编辑 | 编辑源代码]

  • lineWidth:线宽(像素)
  • lineCap:线端样式(butt, round, square
  • lineJoin:转角样式(miter, round, bevel

文本绘制[编辑 | 编辑源代码]

使用fillText(text, x, y)strokeText(text, x, y)方法:

ctx.font = '20px Arial';
ctx.fillStyle = 'green';
ctx.fillText('Hello Canvas!', 50, 150);

图像操作[编辑 | 编辑源代码]

通过drawImage()绘制图像:

const img = new Image();
img.src = 'example.png';
img.onload = function() {
    ctx.drawImage(img, 0, 0, 200, 100);
};

坐标系与变换[编辑 | 编辑源代码]

Canvas使用二维笛卡尔坐标系,原点(0,0)在左上角。可通过以下方法变换坐标系:

  • translate(x, y):平移
  • rotate(angle):旋转
  • scale(x, y):缩放

动画基础[编辑 | 编辑源代码]

使用requestAnimationFrame实现动画:

let x = 0;
function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillRect(x, 100, 50, 50);
    x += 2;
    requestAnimationFrame(animate);
}
animate();

实际应用案例[编辑 | 编辑源代码]

数据可视化(简单柱状图)[编辑 | 编辑源代码]

barChart title 月度销售额 xAxis 月份 yAxis 销售额(万) bar "一月" : 120 bar "二月" : 150 bar "三月" : 180

实现代码:

const data = [120, 150, 180];
const labels = ['一月', '二月', '三月'];

ctx.fillStyle = 'steelblue';
data.forEach((value, index) => {
    const barWidth = 60;
    const barHeight = value;
    const x = 100 + index * 100;
    const y = canvas.height - barHeight;
    
    ctx.fillRect(x, y, barWidth, barHeight);
    ctx.fillStyle = 'black';
    ctx.fillText(labels[index], x, canvas.height - 10);
});

性能优化建议[编辑 | 编辑源代码]

1. 避免频繁的Canvas状态改变(如样式切换) 2. 对复杂图形使用离屏Canvas 3. 使用requestAnimationFrame而非setInterval 4. 清除绘制区域时优先使用clearRect

数学公式应用[编辑 | 编辑源代码]

绘制正弦波示例: y=Asin(2πft+ϕ)

ctx.beginPath();
for (let x = 0; x < canvas.width; x++) {
    const y = 100 + 50 * Math.sin(x * 0.05);
    ctx.lineTo(x, y);
}
ctx.stroke();

总结[编辑 | 编辑源代码]

Canvas提供了强大的2D绘图能力,适合:

  • 数据可视化
  • 游戏开发
  • 图像处理
  • 交互式UI

掌握Canvas基础后,可进一步学习:

  • 高级路径操作(贝塞尔曲线)
  • 像素级操作(ImageData)
  • WebGL集成(三维图形)

通过实践项目(如制作图表、简单游戏)能有效巩固Canvas技能。