答案:在HTML5 Canvas上绘制矩形需获取2D上下文,使用fillRect()填充、strokeRect()描边、clearRect()清除;通过fillStyle、strokeStyle、lineWidth等属性控制颜色与边框,结合路径方法可绘制圆角矩形,并需注意Canvas坐标系及实际尺寸与CSS尺寸的差异以避免显示异常。

要在HTML5 Canvas上绘制矩形,核心是利用其2D渲染上下文提供的方法。最直接的莫过于
fillRect()
strokeRect()
clearRect()
说起在Canvas上画矩形,其实这事儿挺基础,但又无处不在。我个人觉得,理解这几个基本方法,几乎就打开了Canvas绘图的大门。
我们通常会先获取Canvas元素,然后拿到它的2D渲染上下文。这上下文就像你的画笔和颜料盒。
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');拿到
ctx
填充矩形 (fillRect(x, y, width, height)
x
y
width
height
ctx.fillStyle = 'red'; // 设置填充颜色 ctx.fillRect(50, 50, 100, 80);
这里有个小细节,
fillStyle
绘制矩形边框 (strokeRect(x, y, width, height)
strokeRect
fillRect
ctx.strokeStyle = 'blue'; // 设置边框颜色 ctx.lineWidth = 2; // 设置边框宽度 ctx.strokeRect(200, 50, 100, 80);
strokeStyle
lineWidth
清除矩形区域 (clearRect(x, y, width, height)
clearRect
// 假设之前画了一个大矩形,现在想清除中间一块 ctx.clearRect(70, 70, 60, 40);
这在做动画时特别有用,每一帧开始前,我们通常会用
clearRect
我发现很多初学者会混淆这几个,其实它们各司其职,理解它们的功能边界,用起来就顺手多了。
这确实是个好问题,因为光是画个方块,很多时候是不够的。我们希望它有特定的颜色,边框粗细,甚至圆角。
对于颜色和边框,前面提到了
ctx.fillStyle
ctx.strokeStyle
'red'
'#FF0000'
'rgb(255,0,0)'
createLinearGradient
createRadialGradient
createPattern
// 渐变填充 const gradient = ctx.createLinearGradient(0, 0, 100, 0); gradient.addColorStop(0, 'purple'); gradient.addColorStop(1, 'orange'); ctx.fillStyle = gradient; ctx.fillRect(50, 150, 100, 80); // 虚线边框 ctx.strokeStyle = 'green'; ctx.lineWidth = 3; ctx.setLineDash([5, 5]); // 设置虚线模式:5像素实线,5像素空白 ctx.strokeRect(200, 150, 100, 80); ctx.setLineDash([]); // 记得用完清空,否则会影响后续的线条绘制
至于圆角矩形,Canvas原生并没有直接提供
roundRect()
function drawRoundRect(ctx, x, y, width, height, radius) {
ctx.beginPath(); // 开始一条新路径
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.arcTo(x + width, y, x + width, y + radius, radius); // 右上角
ctx.lineTo(x + width, y + height - radius);
ctx.arcTo(x + width, y + height, x + width - radius, y + height, radius); // 右下角
ctx.lineTo(x + radius, y + height);
ctx.arcTo(x, y + height, x, y + height - radius, radius); // 左下角
ctx.lineTo(x, y + radius);
ctx.arcTo(x, y, x + radius, y, radius); // 左上角
ctx.closePath(); // 闭合路径
}
// 绘制一个带圆角的填充矩形
ctx.fillStyle = '#FFD700'; // 金色
drawRoundRect(ctx, 50, 250, 100, 80, 10);
ctx.fill();
// 绘制一个带圆角的边框矩形
ctx.strokeStyle = '#4682B4'; // 钢蓝色
ctx.lineWidth = 2;
drawRoundRect(ctx, 200, 250, 100, 80, 15);
ctx.stroke();你会发现,一旦涉及到更复杂的形状,路径操作
beginPath()
lineTo()
arcTo()
closePath()
fill()
stroke()
没错,坐标系统和尺寸,这真的是Canvas绘图的基石。我见过不少人,包括我自己刚开始的时候,总是在这里犯迷糊。
Canvas的坐标系统是一个二维直角坐标系,原点
(0,0)
当你说
fillRect(50, 50, 100, 80)
(50, 50)
(50, 50)
(50, 50)
一个常见的“陷阱”是关于Canvas元素的CSS尺寸和实际绘图尺寸。HTML中,
<img>
width
height
<canvas width="400" height="300">
canvas { width: 800px; height: 600px; }如果这两个尺寸不一致,Canvas内部的绘图内容会被缩放以适应CSS尺寸。比如,你设置
以上就是canvas如何绘制矩形的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号