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

如何用JavaScript实现多层正方形内嵌套多层圆形的绘制?

实现多层正方形嵌套对应圆形的方案

问题根源

你当前的代码使用了两个独立的canvas元素(Square和Circle),导致正方形和圆形绘制在不同画布上,无法呈现嵌套效果。另外需要确保每个圆形的位置、大小与对应正方形匹配。

修改方案

  1. 只保留一个canvas元素用于绘制所有图形
  2. 将正方形和圆形的绘制逻辑合并到同一个函数中,共享同一个画布上下文
  3. 确保圆形的圆心与对应正方形的中心重合,半径匹配嵌套比例

修改后的完整代码

HTML部分

<canvas id="NestedShape" width="500" height="500" style="border: 5px solid #FF0000;">
Your browser does not support the Canvas tag.
</canvas>

JavaScript部分

function drawNestedShapes() {
  var canvas = document.getElementById("NestedShape");
  if (!canvas.getContext) return;

  var ctx = canvas.getContext("2d");

  // 绘制嵌套正方形
  ctx.fillStyle = "red";
  ctx.fillRect(0, 0, 500, 500);

  ctx.fillStyle = "yellow";
  ctx.fillRect(50, 50, 400, 400);

  ctx.fillStyle = "blue";
  ctx.fillRect(100, 100, 300, 300);

  // 绘制对应嵌套圆形(与你原代码的圆大小一致,中心与正方形重合)
  // 红正方形内的红圆
  ctx.beginPath();
  ctx.arc(250, 250, 125, 0, Math.PI * 2);
  ctx.fillStyle = "red";
  ctx.fill();
  ctx.stroke();
  ctx.closePath();

  // 黄正方形内的黄圆
  ctx.beginPath();
  ctx.arc(250, 250, 75, 0, Math.PI * 2);
  ctx.fillStyle = "yellow";
  ctx.fill();
  ctx.stroke();
  ctx.closePath();

  // 蓝正方形内的蓝圆
  ctx.beginPath();
  ctx.arc(250, 250, 25, 0, Math.PI * 2);
  ctx.fillStyle = "blue";
  ctx.fill();
  ctx.stroke();
  ctx.closePath();
}

// 调用绘制函数
drawNestedShapes();

可选:绘制正方形的内切圆

如果需要每个圆形刚好填满对应正方形的内部(内切圆),只需修改圆形的半径为对应正方形边长的一半:

// 替换原圆形绘制代码为以下内容
// 红正方形内切圆
ctx.beginPath();
ctx.arc(250, 250, 250, 0, Math.PI * 2);
ctx.fillStyle = "red";
ctx.fill();
ctx.stroke();
ctx.closePath();

// 黄正方形内切圆
ctx.beginPath();
ctx.arc(250, 250, 200, 0, Math.PI * 2);
ctx.fillStyle = "yellow";
ctx.fill();
ctx.stroke();
ctx.closePath();

// 蓝正方形内切圆
ctx.beginPath();
ctx.arc(250, 250, 150, 0, Math.PI * 2);
ctx.fillStyle = "blue";
ctx.fill();
ctx.stroke();
ctx.closePath();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 21:52:58