Canvas绘图基于2D渲染上下文,通过命令式API操作路径实现;需先获取ctx = canvas.getContext('2d'),再用fillRect/strokeRect或beginPath+moveTo+lineTo+arc+fill/stroke绘制,配合样式设置与save/restore状态管理。
Canvas 绘图靠的是 2D 渲染上下文(2D context),不是直接画图形,而是通过调用一系列方法,在内存中“描边”或“填充”路径,最终显示在页面上。核心是先获取上下文,再用命令式 API 操作。
必须先拿到 2d 上下文对象,所有绘图操作都通过它进行:
canvas id="myCanvas" width="400" height="300">
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
Canvas 不提供“画矩形”“画圆”这样的高级图形对象,而是封装了常用路径的快捷方法:
ctx.fillRect(x, y, width, height); —— 填充ctx.strokeRect(x, y, width, height); —— 描边ctx.clearRect(x, y, width, height); —— 清空指定区域ctx.beginPath(); —— 开始新路径(必调,否则会累积旧路径)ctx.moveTo(x, y); —— 移动画笔到起点ctx.lineTo(x, y); —— 画直线到目标点ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise); —— 画圆弧(可组合成整圆)ctx.closePath(); —— 自动连线回起点(闭合路径)ctx.fill(); 或 ctx.stroke(); —— 才真正渲染绘图效果由当前上下文状态决定,这些属性影响后续所有绘制:
ctx.fillStyle = '#ff6b6b';(填充色),ctx.strokeStyle = 'blue';(描边色),ctx.globalAlpha = 0.7;
ctx.lineWidth = 3;,ctx.lineCap = 'round';(端点形状),ctx.lineJoin = 'bevel';(连接处样式)ctx.save(); 记录当前样式和变换,ctx.restore(); 回退——适合局部设置,避免污染全局ctx.beginPath();
ctx.arc(200, 150, 50, 0, Math.PI * 2); // 圆心(200,150),半径50
ctx.fillStyle = 'red';
ctx.fill();
ctx.strokeStyle = 'darkred';
ctx.lineWidth = 2;
ctx.stroke();
基本上就这些。Canvas 是“命令式绘图”,关键在于理解路径(path)机制和上下文状态管理。不复杂但容易忽略 beginPath() 和 save()/restore(),导致意外叠加或样式错乱。