← HTML <button> 标签 HTML <caption> 标签 →

HTML <canvas> 图形绘制

原创 2025-09-16 HTML 已有人查阅

HTML <canvas> 图形绘制教程

概述

HTML <canvas> 元素为网页提供了一块位图绘制区域,允许通过 JavaScript 脚本语言动态绘制各种图形。作为 HTML5 的核心功能之一,<canvas> 为开发者提供了强大的图形渲染能力,广泛应用于数据可视化、游戏开发、图像处理和交互式动画等领域。

<canvas> 元素本身仅是一个图形容器,需要配合 JavaScript API 才能实现绘图功能。它采用低层次的过程式模型,支持 2D 形状和位图的程序化渲染。

基本语法与结构

基础示例

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas 基础示例 - 代码号编程学习</title>
</head>
<body>
    <canvas id="drawingCanvas" width="400" height="200"></canvas>

    <script>
        // 获取Canvas元素和绘图上下文
        const canvas = document.getElementById("drawingCanvas");
        const ctx = canvas.getContext("2d");

        // 绘制红色矩形
        ctx.fillStyle = "red";
        ctx.fillRect(50, 50, 100, 50);

        // 绘制蓝色圆形
        ctx.beginPath();
        ctx.arc(300, 100, 30, 0, 2 * Math.PI);
        ctx.fillStyle = "blue";
        ctx.fill();
        ctx.closePath();
    </script>
</body>
</html>

核心概念详解

坐标系系统

Canvas 使用基于左上角原点的坐标系系统:

  • 原点坐标:(0, 0)

  • X轴:从左向右递增

  • Y轴:从上向下递增

渲染上下文

通过 getContext() 方法获取渲染上下文:

const ctx = canvas.getContext("2d");

绘图方法

Canvas API 提供多种绘图方法:

  • fillRect() - 绘制填充矩形

  • strokeRect() - 绘制矩形边框

  • arc() - 绘制圆弧/圆形

  • fillText() - 绘制填充文本

  • strokeText() - 绘制文本轮廓

样式与颜色设置

ctx.fillStyle = "blue";      // 设置填充颜色
ctx.strokeStyle = "#FF0000"; // 设置描边颜色
ctx.lineWidth = 2;           // 设置线宽

路径绘制

路径用于创建复杂形状,基本操作流程:

ctx.beginPath();    // 开始新路径
ctx.moveTo(50, 50); // 移动至起点
ctx.lineTo(150, 50); // 绘制直线
ctx.lineTo(100, 150); // 继续绘制
ctx.closePath();    // 闭合路径
ctx.stroke();       // 描边路径

动画实现

Canvas 支持通过连续重绘实现动画效果:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Canvas动画示例 - 代码号学习编程</title>
</head>
<body>
    <canvas id="animationCanvas" width="400" height="200"></canvas>

    <script>
        const canvas = document.getElementById("animationCanvas");
        const ctx = canvas.getContext("2d");
        let positionX = 0;

        function animate() {
            // 清除画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 绘制移动的矩形
            ctx.fillStyle = "orange";
            ctx.fillRect(positionX, 75, 50, 50);
            
            // 更新位置
            positionX += 2;
            if (positionX > canvas.width) {
                positionX = -50;
            }
            
            // 请求下一帧动画
            requestAnimationFrame(animate);
        }

        animate(); // 启动动画
    </script>
</body>
</html>

图形绘制实践

矩形绘制

<canvas id="rectCanvas" width="250" height="150" style="border:1px solid #ddd;">
    您的浏览器不支持Canvas元素
</canvas>

<script>
    const canvas = document.getElementById("rectCanvas");
    const ctx = canvas.getContext("2d");
    ctx.fillStyle = "#FF0000";
    ctx.fillRect(0, 0, 200, 100);
</script>

直线绘制

<canvas id="lineCanvas" width="200" height="100" style="border:1px solid #ddd;">
    您的浏览器不支持Canvas元素
</canvas>

<script>
    const canvas = document.getElementById("lineCanvas");
    const ctx = canvas.getContext("2d");
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(200, 100);
    ctx.strokeStyle = "green";
    ctx.stroke();
</script>

圆形绘制

<canvas id="circleCanvas" width="200" height="100" style="border:1px solid #ddd;">
    您的浏览器不支持Canvas元素
</canvas>

<script>
    const canvas = document.getElementById("circleCanvas");
    const ctx = canvas.getContext("2d");
    ctx.beginPath();
    ctx.arc(100, 50, 40, 0, 2 * Math.PI);
    ctx.strokeStyle = "purple";
    ctx.stroke();
</script>

文本绘制

填充文本

<canvas id="fillTextCanvas" width="300" height="100" style="border:1px solid #ddd;">
    您的浏览器不支持Canvas元素
</canvas>

<script>
    const canvas = document.getElementById("fillTextCanvas");
    const ctx = canvas.getContext("2d");
    ctx.font = "30px Arial";
    ctx.fillStyle = "navy";
    ctx.fillText("代码号学习编程", 10, 50);
</script>

描边文本

<canvas id="strokeTextCanvas" width="300" height="100" style="border:1px solid #ddd;">
    您的浏览器不支持Canvas元素
</canvas>

<script>
    const canvas = document.getElementById("strokeTextCanvas");
    const ctx = canvas.getContext("2d");
    ctx.font = "30px Arial";
    ctx.strokeStyle = "darkred";
    ctx.strokeText("代码号编程实践", 10, 50);
</script>

图像绘制

Canvas 支持绘制外部图像:

const img = new Image();
img.src = "https://www.ebingou.cn/biancheng/images/1.jpg";
img.onload = function() {
    ctx.drawImage(img, 0, 0, 200, 100);
};

实际应用示例

数据可视化图表

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>数据可视化示例 - 代码号编程学习</title>
</head>
<body>
    <canvas id="chartCanvas" width="400" height="300"></canvas>

    <script>
        const canvas = document.getElementById("chartCanvas");
        const ctx = canvas.getContext("2d");
        
        // 示例数据
        const data = [120, 150, 180, 90, 200];
        const colors = ["#4CAF50", "#2196F3", "#FF9800", "#E91E63", "#9C27B0"];
        
        // 绘制柱状图
        const barWidth = 50;
        const spacing = 20;
        const startX = 50;
        
        data.forEach((value, index) => {
            ctx.fillStyle = colors[index];
            ctx.fillRect(
                startX + index * (barWidth + spacing),
                300 - value,
                barWidth,
                value
            );
            
            // 添加数据标签
            ctx.fillStyle = "black";
            ctx.font = "12px Arial";
            ctx.fillText(value, startX + index * (barWidth + spacing) + 15, 290 - value);
        });
    </script>
</body>
</html>

本节课程知识要点

  1. Canvas 基础:理解 Canvas 作为位图绘制容器的基本概念和作用域

  2. 坐标系系统:掌握基于左上角原点的二维坐标系

  3. 绘图上下文:学会获取和使用 2D 渲染上下文

  4. 基本图形绘制:熟练掌握矩形、圆形、直线等基本图形的绘制方法

  5. 路径操作:理解路径的创建、绘制和闭合流程

  6. 文本渲染:掌握填充文本和描边文本的不同应用场景

  7. 动画原理:了解基于 requestAnimationFrame 的动画实现机制

  8. 图像处理:学会在 Canvas 中加载和绘制外部图像

进阶学习建议

  1. 性能优化:对于复杂动画,注意使用离屏 Canvas 进行预渲染

  2. 事件处理:实现 Canvas 元素的交互功能,如点击、拖拽检测

  3. 高级高效:探索渐变、阴影、合成操作等高级渲染特性

  4. 第三方库:了解 Fabric.js、Konva.js 等 Canvas 扩展库的使用

Canvas 技术为网页图形开发提供了强大基础,通过不断实践可以创建出丰富的交互式视觉体验。更多详细教程和示例代码,请访问代码号教程中心:https://www.ebingou.cn/jiaocheng/

← HTML <button> 标签 HTML <caption> 标签 →
分享笔记 (共有 篇笔记)
验证码:
微信公众号