首页 > 解决方案 > 如何将对象绘制到画布上?

问题描述

所以基本上我想通过类让一个对象出现在一个简单的 HTML 画布上GameObject,但我无法完成。代码编译得很好,但它只是没有出现在屏幕上。我认为它与变量有关,ctx但我不太确定。

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

square = new GameObject(20, 40, 50, 50, "blue");
square.drawObject();

class GameObject {
    constructor(x, y, w, h, color) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.color = color;
    }

     drawObject() {
        ctx.rect(this.x, this.y, this.w, this.h);
        ctx.fillStyle = this.color;
        ctx.fill();
    }
}
<style>
    * { padding: 0; margin: 0; }
    canvas { background: #eee; display: block; margin: 0 auto; }
</style>

<canvas id="myCanvas" width="480" height="320"></canvas>

标签: javascripthtmlcssdomcanvas

解决方案


在定义之前,您不能使用 JS 类。如果您将方形游戏对象的初始化移到GameObject类定义下方,则它可以工作:

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

class GameObject {
    constructor(x, y, w, h, color) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.color = color;
    }

     drawObject() {
        ctx.rect(this.x, this.y, this.w, this.h);
        ctx.fillStyle = this.color;
        ctx.fill();
    }
}

square = new GameObject(20, 40, 50, 50, "blue");
square.drawObject();
* { padding: 0; margin: 0; }
canvas { background: #eee; display: block; margin: 0 auto; }
<canvas id="myCanvas" width="480" height="320"></canvas>


推荐阅读