Canvas绘图需先获取2D上下文,再用fillRect()、strokeRect()、clearRect()绘制矩形,或通过beginPath()、moveTo()、lineTo()、stroke()绘制线条,并提前设置fillStyle、strokeStyle等样式。

准备画布与绘图上下文
先在 HTML 中定义 <canvas></canvas> 元素,设置宽高(推荐显式声明 width/height 属性,避免缩放失真):
<canvas id="myCanvas" width="400" height="300">浏览器不支持 Canvas</canvas>
然后在 JavaScript 中获取 2D 绘图上下文:
const canvas = document.getElementById('myCanvas');<br>const ctx = canvas.getContext('2d');
⚠️ 注意:必须用 getContext('2d'),否则无法绘图。
绘制矩形的三种方式
Canvas 提供三个专用矩形方法,参数统一为 (x, y, width, height),其中 (x, y) 是左上角坐标:
生成可在 deepbi 沙箱 iframe 内运行或作为独立文件运行的交互式 HTML 页面,使用 `window.deepbi` JS SDK 实现数据查询、空间管理、文件浏览及用户操作。当用户提出以下需求时启用该能力: - 创建 KPI 仪表盘、数据表格、文件浏览器、成员列表、管理页面; - 明确要求“转成 dhtml”、“转译成 HTML”、“把 XX 页面转成……”、“控制台页面”、“管理后台”、“DeepBI 页面迁移”; - 提及位于 `apps/console/src/featur
-
填充矩形:用
fillRect(),颜色由ctx.fillStyle控制ctx.fillStyle = '#3498db';<br>ctx.fillRect(20, 30, 120, 80);
-
描边矩形:用
strokeRect(),线宽和颜色由ctx.lineWidth和ctx.strokeStyle控制ctx.strokeStyle = '#e74c3c';<br>ctx.lineWidth = 4;<br>ctx.strokeRect(160, 30, 120, 80);
-
清除矩形区域:用
clearRect(),让指定区域变透明(常用于动画擦除)ctx.clearRect(50, 50, 60, 40);
绘制线条的基本流程
线条需通过路径(path)构建,关键四步不能少:
- 调用
beginPath()开启新路径(防止旧路径干扰) - 用
moveTo(x, y)定位起点 - 用
lineTo(x, y)连接后续点(可多次调用画折线) - 最后用
stroke()实际绘制(仅描边)或fill()(若路径闭合且需填充)
示例:画一条从 (50,100) 到 (250,100) 的蓝色横线
ctx.beginPath();<br>ctx.moveTo(50, 100);<br>ctx.lineTo(250, 100);<br>ctx.strokeStyle = '#2ecc71';<br>ctx.lineWidth = 3;<br>ctx.stroke();
延伸:连三个点可画三角形,加 closePath() 后用 fill() 就能填充。
样式控制要点
颜色、粗细等样式需在绘图前设置,且对后续同类型操作生效:
- 填充色:
ctx.fillStyle = 'red'或'#ff6b6b'或'rgba(255,107,107,0.8)' - 描边色:
ctx.strokeStyle = 'purple' - 线宽:
ctx.lineWidth = 2(单位像素,不随缩放变化) - 线端样式(可选):
ctx.lineCap = 'round'(butt / round / square)
注意:fillStyle 影响 fillRect() 和 fill(),strokeStyle 和 lineWidth 只影响 strokeRect() 和 stroke()。

















