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

求助:Canvas中JavaScript绘制圆形无显示问题排查与修复

问题修复方案

你的代码里有几个关键错误导致圆形无法显示:

  1. Canvas宽高赋值语法错误:canvas.width = innerWidth canvas.height = innerHeight 缺少分号,JS解析会出错,修正为:
canvas.width = innerWidth;
canvas.height = innerHeight;
  1. Player类的constructor未闭合:constructor方法的结束大括号缺失,导致类定义不完整,JS无法正确解析Player类。

  2. ctx.arc参数顺序完全错误:arc方法的正确参数顺序是(x, y, radius, startAngle, endAngle, anticlockwise),你错误地把颜色参数插到了中间,且未设置填充颜色。需要先通过ctx.fillStyle指定颜色,再调用fill()。

修复后的完整JS代码:

const canvas = document.getElementById("game-canvas");
const ctx = canvas.getContext('2d');

canvas.width = innerWidth;
canvas.height = innerHeight;

class Player { 
    constructor(x, y, radius, color) {
        this.x = x;
        this.y = y;
        this.radius = radius;  
        this.color = color;
    } // 补上constructor的闭合括号
    draw() {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2); // 修正arc参数顺序
        ctx.fillStyle = this.color; // 设置填充颜色
        ctx.fill();
    }
}
const player = new Player(100, 100, 50, 'blue'); // 半径改小避免超出可视区域(可选)
player.draw();
console.log(player);

额外建议:把JS代码放到HTML的<body>末尾,或者用DOMContentLoaded事件包裹,确保DOM加载完成后再执行脚本,避免偶发的canvas获取失败问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 21:08:30