You need to enable JavaScript to run this app. 如何基于JSON数据在Canvas中绘制水平排列的多矩形,避免硬编码ctx.rect参数
优惠活动
大模型
产品
解决方案
定价
更多

如何基于JSON数据在Canvas中绘制水平排列的多矩形,避免硬编码ctx.rect参数

Canvas动态生成水平排列矩形实现方案

你可以通过遍历JSON数据、动态计算每个矩形的水平偏移量的方式实现,无需硬编码坐标和尺寸,具体实现逻辑如下:

  • 先设定初始参数:第一个矩形的起始X坐标、统一的Y坐标、矩形之间的横向间距
  • 遍历JSON数组,每绘制完一个矩形后,将当前X坐标累加「当前矩形宽度 + 横向间距」,作为下一个矩形的起始X坐标
  • 绘制时直接读取数据项中的width、height、bgColor、name等属性赋值即可

修改后的完整代码如下:

<canvas id="NodeList" width="900" height="2000"></canvas>
<script>
    var data = [{
            "name": "1",
            "x": 225,
            "y": 197,
            "width": 121,
            "height": 67,
            "bgColor": "#00FF00",
            "radius": 2,
            "version": "1.0.0"
        },
        {
            "name": "2",
            "x": 225,
            "y": 297,
            "width": 121,
            "height": 67,
            "bgColor": "#00FF00",
            "radius": 2
        },    
        {
            "name": "3",
            "x": 225,
            "y": 397,
            "width": 121,
            "height": 67,
            "bgColor": "#00FF00",
            "radius": 2
        },
        {
            "name": "4",
            "x": 225,
            "y": 497,
            "width": 121,
            "height": 67,
            "bgColor": "#00FF00",
            "radius": 2
        },    
        {
            "name": "5",
            "x": 225,
            "y": 597,
            "width": 121,
            "height": 67,
            "bgColor": "#00FF00",
            "radius": 2
        }    
    ];
    var c = document.getElementById("NodeList");
    var ctx = c.getContext("2d");

    // 动态生成水平排列矩形
    let currentX = 20; // 第一个矩形的起始X坐标
    const startY = 21; // 所有矩形统一的Y坐标
    const gap = 7; // 矩形之间的横向间距

    data.forEach(item => {
        // 设置填充色
        ctx.fillStyle = item.bgColor;
        // 绘制矩形路径
        ctx.rect(currentX, startY, item.width, item.height);
        // 填充矩形背景(不需要填充可删除此行)
        ctx.fillRect(currentX, startY, item.width, item.height);
        // 绘制矩形内的名称文字
        ctx.fillStyle = "#000"; // 文字颜色可自行调整
        ctx.fillText(item.name, currentX + 5, startY + 15);
        // 计算下一个矩形的X坐标
        currentX += item.width + gap;
    })

    ctx.stroke();
</script>

如果需要保留原有对角线矩形逻辑,直接在动态绘制逻辑前保留对应代码即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 05:45:04