You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Canvas JavaScript绘制多层嵌套圆形

如何实现多层嵌套圆形绘制?

你的代码存在几个问题导致无法正确绘制多层嵌套圆形,以下是修正后的完整代码及问题说明:

修正后的完整代码

<!DOCTYPE html>
<html>
<head>
    <title>多层嵌套圆形</title>
    <script type="text/javascript">
        function drawNestedCircles() {
            const canvas = document.getElementById("Circle");
            if (canvas.getContext) {
                const ctx = canvas.getContext("2d");
                // 最外层黄色圆形
                ctx.beginPath();
                ctx.arc(250, 250, 160, 0, Math.PI * 2);
                ctx.fillStyle = "yellow";
                ctx.fill();
                ctx.stroke();
                ctx.closePath();

                // 中间红色圆形
                ctx.beginPath();
                ctx.arc(250, 250, 70, 0, Math.PI * 2);
                ctx.fillStyle = "red";
                ctx.fill();
                ctx.stroke();
                ctx.closePath();

                // 内层蓝色描边圆环
                ctx.beginPath();
                ctx.arc(250, 250, 20, 0, Math.PI * 2);
                ctx.strokeStyle = "blue";
                ctx.lineWidth = 25;
                ctx.stroke();
                ctx.closePath();
            }
        }
    </script>
</head>
<body onload="drawNestedCircles()">
    <h1>使用Canvas绘制多层嵌套圆形</h1>
    <canvas id="Circle" width="500" height="500" style="border: 1px solid black;">
        你的浏览器不支持Canvas标签。
    </canvas>
</body>
</html>

关键修复点

  • 变量名统一:原代码混用circle和ctx两个上下文变量,导致蓝色圆环样式无法生效,现在全程统一使用ctx
  • 调整绘制顺序:原代码先画红色小圆形再画黄色大圆形,黄色会完全覆盖红色,改为从外层到内层的绘制顺序,确保每层圆形正常显示
  • 补充stroke()调用:原代码中蓝色圆环仅设置样式但未调用stroke()方法,导致圆环无法渲染
  • 清理冗余语法:移除arc()方法末尾多余的逗号,保证代码语法规范

内容的提问来源于stack exchange,提问作者Ksusha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 05:53:19