如何获取Canvas中圆/圆弧端点的x、y坐标以绘制轮辐?
问题:Canvas绘制车轮轮辐,让线条终止于内圆
刚接触JavaScript的Canvas对象,试图绘制类似车轮轮辐的线条。目前可以实现从外圆边缘到圆心的线条,但无法让线条终止于内圆(轮毂)。
现有代码
<!DOCTYPE html> <html lang="en" dir="ltr"> <body> <script type="text/javascript"> const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); document.body.appendChild(canvas); ctx.beginPath(); ctx.strokeStyle = "black"; ctx.arc(75, 75, 70, 0, 2 * Math.PI); ctx.arc(75, 75, 20, 0, 2 * Math.PI); var part = ( 2 * Math.PI ) / 8; for( i=1; i<=8; i++ ) { ctx.arc(75, 75, 70, 0, (part*i) ); ctx.lineTo( 75, 75 ); } ctx.stroke(); </script> </body> </html>
当前效果

我知道可以通过数学计算得到这些坐标,但希望有更简便的方法。请问是否可以将圆弧端点的位置转换为对应的x、y坐标?
解决方案
Canvas没有直接提供获取圆弧端点坐标的快捷API,但用三角函数计算端点坐标其实非常直接,一点也不繁琐,这也是实现需求的最优方式。
核心公式:对于圆心(cx, cy)、半径r、角度theta(弧度制),端点坐标为:
x = cx + r * Math.cos(theta)y = cy + r * Math.sin(theta)
修改后的代码可以直接绘制从外圆到内圆的轮辐:
<!DOCTYPE html> <html lang="en" dir="ltr"> <body> <script type="text/javascript"> const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); document.body.appendChild(canvas); ctx.beginPath(); ctx.strokeStyle = "black"; // 绘制外圆与内圆 const cx = 75, cy = 75; const outerRadius = 70; const innerRadius = 20; ctx.arc(cx, cy, outerRadius, 0, 2 * Math.PI); ctx.arc(cx, cy, innerRadius, 0, 2 * Math.PI); // 绘制轮辐 const spokeCount = 8; const angleStep = (2 * Math.PI) / spokeCount; for(let i = 0; i < spokeCount; i++) { const angle = i * angleStep; // 计算外圆端点 const outerX = cx + outerRadius * Math.cos(angle); const outerY = cy + outerRadius * Math.sin(angle); // 计算内圆端点 const innerX = cx + innerRadius * Math.cos(angle); const innerY = cy + innerRadius * Math.sin(angle); // 绘制单根轮辐 ctx.moveTo(outerX, outerY); ctx.lineTo(innerX, innerY); } ctx.stroke(); </script> </body> </html>
关键优化点
- 用
moveTo直接定位外圆端点,再lineTo内圆端点,避免绘制到圆心 - 角度从0开始循环,避免重复绘制轮辐
- 抽离常量参数,后续修改轮辐数量、半径等更便捷
内容的提问来源于stack exchange,提问作者hennep
相关产品推荐
相关产品推荐

