上一篇
html5画圆js
- 行业动态
- 2025-05-12
- 4
在HTML5 Canvas中使用
context.arc(x,y,r,0,2π)
配合 fill()
或 stroke()
方法即可
环境准备
使用HTML5 <canvas>
元素结合JavaScript绘制圆形,需确保浏览器支持HTML5。
绘制圆形基本步骤
- 创建Canvas元素:在HTML中添加
<canvas>
标签,并设置宽高。 - 获取渲染上下文:通过
getContext('2d')
获取2D绘图环境。 - 设置绘制参数:定义填充色、描边色、线宽等。
- 调用
arc()
方法:指定圆心坐标、半径、起止角度和绘制方向。 - 填充或描边:使用
fill()
或stroke()
完成绘制。
代码示例与解析
<!DOCTYPE html> <html lang="zh"> <body> <canvas id="myCanvas" width="300" height="300" style="border:1px solid #000;"></canvas> <script> // 获取Canvas元素 const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); // 设置填充颜色为蓝色 ctx.fillStyle = 'blue'; // 绘制圆形(参数:圆心x,圆心y,半径,起始角,结束角,顺时针方向) ctx.arc(150, 150, 100, 0, 2 Math.PI, true); // 填充圆形 ctx.fill(); // 设置描边颜色和线宽 ctx.strokeStyle = 'red'; ctx.lineWidth = 5; // 重新绘制圆形路径 ctx.beginPath(); ctx.arc(150, 150, 80, 0, 2 Math.PI, false); // 描边圆形 ctx.stroke(); </script> </body> </html>
代码步骤 | 作用描述 |
---|---|
ctx.fillStyle = 'blue' | 设置填充颜色为蓝色 |
ctx.arc(150, 150, 100, 0, 2π, true) | 以(150,150)为圆心,半径100,顺时针画完整圆 |
ctx.fill() | 填充当前路径为实心圆 |
ctx.strokeStyle = 'red' | 设置描边颜色为红色 |
ctx.lineWidth = 5 | 设置描边线条宽度为5px |
ctx.beginPath() | 新建路径(清除之前路径) |
ctx.arc(...) | 绘制半径80的空心圆 |
ctx.stroke() | 描边当前路径 |
arc()
方法参数详解
参数序号 | 参数名称 | 说明 |
---|---|---|
1 | x | 圆心横坐标(相对于Canvas左边界) |
2 | y | 圆心纵坐标(相对于Canvas上边界) |
3 | radius | 圆的半径(非直径) |
4 | startAngle | 起始角度(弧度制,0为右水平轴,逆时针增加) |
5 | endAngle | 结束角度(同startAngle规则) |
6 | anticlockwise | 布尔值,是否逆时针绘制(默认false为顺时针) |
常见问题与解答
问题1:为什么arc()
绘制后没有显示?
解答:需调用fill()
或stroke()
方法执行填充/描边操作,未调用时,仅创建路径但不会渲染图形。
问题2:如何绘制多个同心圆?
解答:
- 调整
arc()
的半径参数(如80→60→40)。 - 重复
beginPath()
→arc()
→stroke()
流程。 - 可修改
lineWidth
或fillStyle
区分不同圆环。
示例代码:for(let r=100; r>=30; r-=20){ ctx.beginPath(); ctx.arc(150,150,r,0,2π); ctx.strokeStyle = `rgba(0,0,255,${r/100})`; // 半透明蓝色 ctx.lineWidth = r/20; ctx