Canvas 是 HTML 提供的命令式绘图元素,需通过 JavaScript 的 2D 上下文(getContext('2d'))调用 fillRect、arc 等方法绘制图形,并设置 fillStyle、strokeStyle 等样式属性;清空画布可用 canvas.width = canvas.width 或 clearRect。

它不是 SVG,不生成 DOM 节点;也不是 div + CSS,不能靠样式堆出图形——它是命令式绘图:你告诉它“从哪开始、画什么、怎么填”,它就照做。
怎么启用 canvas?
先在 HTML 里放一个 标签,指定宽高(最好用 width/height 属性,别只靠 CSS 缩放):
然后用 JS 获取上下文(2D 绘图用 getContext('2d')):
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
怎么画基本图形?
所有绘制都通过 ctx 对象调用方法。记住两个关键步骤:描边(stroke) 和 填充(fill),很多图形默认只描边,不填色就看不见。
立即学习“Java免费学习笔记(深入)”;
-
画矩形:直接用
fillRect(x, y, width, height)或strokeRect(...) -
画路径(线、三角形、圆弧等):先
beginPath(),再用moveTo()、lineTo()、arc()等“画线”,最后stroke()或fill() -
画圆:用
arc(x, y, radius, startAngle, endAngle),注意角度单位是弧度(比如 π 就是Math.PI),画完要closePath()才能正确填充
怎么设置颜色和样式?
这些属性在绘制前设好,影响后续所有操作:
-
ctx.fillStyle = '#ff6b6b'—— 填充色(矩形 fill / 路径 fill) -
ctx.strokeStyle = 'blue'—— 描边色(strokeRect / stroke) -
ctx.lineWidth = 2—— 描边粗细 -
ctx.lineCap = 'round'—— 线端样式('butt'/'round'/'square') -
ctx.globalAlpha = 0.7—— 整体透明度(0~1)
怎么清空画布?
最可靠的方式是重设宽高(会清空并重置所有样式):
canvas.width = canvas.width; // 简洁写法,触发重置
或者用 clearRect(0, 0, canvas.width, canvas.height),但不会重置线条宽度、颜色等状态。
基本上就这些。canvas 不复杂,但容易忽略路径管理(比如忘了 beginPath() 导致图形连在一起)和坐标系原点(左上角)。多练几次矩形、线条、圆,后面画图表、游戏、滤镜就顺了。











