为什么 .fillStyle 不更新我的 canvas 背景

Why wont .fillStyle update my canvas background

我正在使用静态方法创建 Canvas class,将 canvas 绘制到文档并更改 canvas 的背景颜色。

将 canvas 添加到主体中工作正常,但背景颜色没有改变。

我可以更改 fillStyle 属性 使用 canvas.context.fillStyle = "#123456" 和日志记录 canvas.context.fillStyle 输出 #123456.

但是当我log CanvasRenderingContext2D fillStyle 属性 没有改变。

请参阅下面的控制台输出。

看下面的代码

export default class Canvas{

    static canvas = null;
    static context = null;
    static backgroundColor = '#0000ff';

    static drawCanvas(){
        Canvas.canvas = document.createElement('canvas');
        Canvas.context = Canvas.canvas.getContext('2d');
        Canvas.setBackgroundColor(Canvas.backgroundColor);
        document.body.append(Canvas.canvas);
    }


    static setBackgroundColor(bgColor){
        Canvas.backgroundColor = bgColor;

        if (Canvas.context != null) {
            Canvas.context.fillStyle = Canvas.backgroundColor;
            Canvas.context.fillRect(0,0, Canvas.canvas.width, Canvas.canvas.height);

            // See screenshot for console output
            console.log(Canvas.context.fillStyle) // Outputs: #0000ff
            console.log(Canvas.context) // fillstyle outputs: #000000
        }
    }
}

有几点可能值得一提:

  1. 其他方法设置的宽高(未显示)
  2. 我可以在 CSS 中调整边框和背景颜色(但我想在 JavaScript 中这样做)。

原来我必须在附加 canvas 之后设置背景颜色。

见下文

    static drawCanvas(){
        Canvas.canvas = document.createElement('canvas');
        Canvas.context = Canvas.canvas.getContext('2d');
        // Append Canvas before setting background
        document.body.append(Canvas.canvas);
        Canvas.setBackgroundColor(Canvas.backgroundColor);
    }