繁体   English   中英

如何将对象绘制到 canvas?

[英]How to draw objects to canvas?

所以基本上我想让一个 object 出现在一个简单的 HTML GameObject通过 ZA2F2ED4F8EBC2CBB4C21A29DC40AB6 完成它。 代码编译得很好,但它只是没有出现在屏幕上。 我认为它与变量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 类。 如果将方形游戏 object 的初始化移动到GameObject class 定义的下方,它可以工作:

 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>

使用前只需初始化 class 即可。

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

 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 Class Object 中声明变量。 重要的是要记住类只能包含方法。 这在过去也让我绊倒了。 这可能是您在 canvas 上一无所获的原因。 您是否收到任何错误消息? 查看这些参考资料: ES6 class 变量替代这里是关于对象的一章,它显示了 ES5 和 ES6 Class 对象之间的区别。 https://eloquentjavascript.net/06_object.html

我希望这有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM