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

Canvas画布中方块未显示:原因排查与解决方法咨询

Canvas方块不显示的问题修复

问题原因

  • fillRect(x, y, width, height) 方法的宽度和高度参数被设为0, 0,没有面积的矩形无法在画布上呈现。
  • 你提到要绘制两个方块,但当前代码仅执行了一次填充矩形的操作,缺少第二个方块的绘制逻辑。

修复方案

  1. 将fillRect的宽度和高度改为大于0的数值,比如100, 100,让矩形具备可见的尺寸。
  2. 若需要两个方块,添加第二次填充矩形的代码,可通过修改位置或颜色来区分两个方块。

修复后的示例代码

const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");

function draw() {      
        // 第一个红色方块
        context.fillStyle = "rgb(200, 0, 0)";
        context.fillRect(50, 50, 100, 100);
        
        // 第二个蓝色方块
        context.fillStyle = "rgb(0, 0, 200)";
        context.fillRect(200, 50, 100, 100);
};

draw();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:41:41