⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

JS Canvas绘图

学习Canvas API · 难度:进阶 · +15XP

JavaScript Canvas 绘图入门

Canvas(画布)是 HTML5 提供的 2D 绘图 API,通过 JavaScript 在 <canvas> 元素上绘制图形、文字、图像和动画。Canvas 是位图渲染,每个像素都可以独立控制,广泛用于数据可视化、游戏开发、图像处理、动画效果等场景。

Canvas 基础设置

  1. 在 HTML 中添加 <canvas> 元素并设置宽高
  2. 通过 getContext("2d") 获取 2D 渲染上下文
  3. 使用上下文对象的方法进行绘制
<!-- HTML -->
<canvas id="myCanvas" width="500" height="400"></canvas>

// JavaScript: 获取上下文 const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d");

// 注意:canvas 尺寸通过 width/height 属性设置(不是 CSS 样式) // CSS 样式会缩放画布而不会改变分辨率

绘制图形

功能方法说明
矩形(填充)fillRect(x, y, w, h)绘制填充矩形
矩形(描边)strokeRect(x, y, w, h)绘制矩形边框
清除区域clearRect(x, y, w, h)擦除指定区域
圆形/弧线arc(x, y, r, start, end)绘制圆弧
线条moveTo/lineTo绘制路径
const ctx = document.getElementById("c").getContext("2d");

// 绘制填充矩形 ctx.fillStyle = "blue"; ctx.fillRect(20, 20, 150, 100);

// 绘制描边矩形 ctx.strokeStyle = "red"; ctx.lineWidth = 3; ctx.strokeRect(200, 20, 150, 100);

// 绘制圆形(使用 arc + 路径) ctx.beginPath(); ctx.arc(100, 250, 50, 0, Math.PI * 2); ctx.fillStyle = "green"; ctx.fill(); ctx.strokeStyle = "darkgreen"; ctx.stroke();

// 绘制线条(路径方式) ctx.beginPath(); ctx.moveTo(50, 350); // 起点 ctx.lineTo(200, 350); // 画线到 ctx.lineTo(125, 380); // 画线到 ctx.closePath(); // 闭合路径 ctx.fillStyle = "orange"; ctx.fill(); ctx.stroke();

绘制文字与渐变

// 绘制文字
ctx.font = "bold 30px Arial";
ctx.fillStyle = "purple";
ctx.textAlign = "center";
ctx.fillText("Hello Canvas!", 250, 50);

ctx.font = "20px serif"; ctx.strokeStyle = "navy"; ctx.strokeText("描边文字", 250, 90);

// 线性渐变 const gradient = ctx.createLinearGradient(300, 120, 450, 220); gradient.addColorStop(0, "red"); gradient.addColorStop(0.5, "yellow"); gradient.addColorStop(1, "blue"); ctx.fillStyle = gradient; ctx.fillRect(300, 120, 150, 100);

// 径向渐变 const radGrad = ctx.createRadialGradient(400, 300, 10, 400, 300, 60); radGrad.addColorStop(0, "white"); radGrad.addColorStop(1, "black"); ctx.fillStyle = radGrad; ctx.beginPath(); ctx.arc(400, 300, 60, 0, Math.PI * 2); ctx.fill();

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 231 篇
0 完成
🔥 0