提问者:小点点

在javascript中通过类绘制对象


所以基本上我想通过类GameObject使一个对象出现在一个简单的HTML画布上,但我做不到。 代码编译得很好,但它只是不显示在屏幕上。 我假设它与变量ctx有关,但我不太确定。 另外,我对javascript不是很有经验。

null

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

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

square.drawObject();

class GameObject {
    x;
    y;
    w;
    h;
    color;
    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();
    }
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Test</title>
    <style>
        * { padding: 0; margin: 0; }
        canvas { background: #eee; display: block; margin: 0 auto; }
    </style>
</head>
<body>

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

<script src="App.js"></script>

</body>
</html>

null


共3个答案

匿名用户

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

null

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>

匿名用户

只需在使用类之前对其进行初始化即可。

另外一点是,您不需要设置x,y,w,h,color,因为您是在构造函数中设置的。

null

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();
    }
}

const square = new GameObject(20, 40, 50, 50, "blue");
square.drawObject();
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Test</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        canvas {
            background: #eee;
            display: block;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="480" height="320"></canvas>

    <script src="index.js"></script>
</body>
</html>

匿名用户

您可能会混淆ES5类和ES6。 我不是JS方面的专家,我需要做一些挖掘自己在这个主题上。 这是我想出来的。 而且,我希望有更多专业知识的人来帮忙。 不能在ES6类对象中声明变量。 重要的是要记住类只能包含方法。 这在过去也曾使我绊倒过。 这可能就是你没有在画布上得到任何东西的原因。 你收到任何错误信息了吗? 查看这些参考资料:ES6类变量备选项这里是关于对象的一章,它展示了ES5和ES6类对象之间的区别。 https://eloquentJavaScript.net/06_object.html

我希望这能帮上忙!