javascript - 如何将对象绘制到画布上?
问题描述
所以基本上我想通过类让一个对象出现在一个简单的 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>
解决方案
在定义之前,您不能使用 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>
推荐阅读
- sql - SQL 过程按给定百分比计算列
- cpanel - 跟踪从 cPanel 终端对系统的访问
- abp - 使用带有 abp 的 ocelot 时如何将租户 ID 发送到下游服务
- javascript - 如何使用javascript将excel中的工作表保存为新的excel文件
- javascript - 无法从主动选择反应参数传递多选复选框值
- keras - 如何在带有 tensorflow 2 keras 的自定义 train_step 中使用 if 条件
- algorithm - 当数组大小为常数值时对数组进行排序的时间复杂度
- php - 如何在 Laravel 中使用代码状态码 404 抛出 NotFoundResourceException
- r - 使用 R 对具有重复 K 倍的数据集使用逻辑回归
- r - 如何纠正cut方法的错误结果?