javascript - 用 html 和 javascript 编写画布
问题描述
我正在尝试用 html 和 javascript 编写游戏,为此我决定使用画布,因为它会使开发更容易。但是,当我尝试在画布中实现另一个对象时,代码似乎中断了,我一直在摆弄代码,以便看到问题,但是到目前为止我还没有成功。代码可以在下面找到:
<!DOCTYPE html>
<html>
<head>
<Title>Game Prototype 1</Title>
</head>
<body onload= "startGame()">
<canvas id="canvas"
style =
"border:1px solid #000000;
padding-left: 0;
padding-right: 0;
margin-top: 65px;
margin-left: auto;
margin-right: auto;
display: block;">
</canvas>
<script>
var character;
function startGame(){
gameArea.start();
character = new character(30, 30, "red", 10, 120);
}
var gameArea = {
canvas:
document.getElementById("canvas");
start : function() {
this.canvas.width = 1000;
this.canvas.height = 800;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas,document.body.childNodes[0]);
}
function character(width, height, color, x, y) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
ctx = gameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.width, this.height, this.x, this.y);
}
</script>
</body>
</html>
代码的输出是这样的:
在这一点上,我不再确定问题是哪个字符变量,因此字符没有被显示,或者与画布有关,因为画布的尺寸不正确,我不完全确定为什么画布会改变尺寸(如果屏幕上显示的矩形是画布)。这就是我所说的代码破坏的意思。
解决方案
对象中有一些语法错误gameArea
。(}
缺少 A,在 Javascript 中,您使用,
而不是;
分隔对象中的成员。)
我建议使用浏览器控制台来发现此类问题。这是固定对象的代码:
<!DOCTYPE html>
<html>
<head>
<Title>Game Prototype 1</Title>
</head>
<body onload= "startGame()">
<canvas id="canvas"
style =
"border:1px solid #000000;
padding-left: 0;
padding-right: 0;
margin-top: 65px;
margin-left: auto;
margin-right: auto;
display: block;">
</canvas>
<script>
var character;
function startGame(){
gameArea.start();
character = new character(30, 30, "red", 10, 120);
}
var gameArea = {
canvas: document.getElementById("canvas"),
start: function() {
this.canvas.width = 1000;
this.canvas.height = 800;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas,document.body.childNodes[0]);
}
}
function character(width, height, color, x, y) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
ctx = gameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.width, this.height, this.x, this.y);
}
</script>
</body>
</html>
这是否解决了您的问题,或者您是否期望发生其他事情?
推荐阅读
- html - Pros Vs Cons of using multiple div overlays instead of separate pages?
- ios - Apple 拒绝了我的应用程序,因为它在应用程序启动时崩溃了……但我无法模仿
- python - Collapsing rows in a Dataframe into one specific row to fill missing values?
- laravel - Laravel Voyager 更改 RichTextBox 的背景
- javascript - 如何将 datepicker 值设置为 firebase?
- python - 如何绘制具有不同形状的聚类和不同颜色的原始类的聚类输出?
- python - 运行打印功能时Pycharm ImportError?
- node.js - NodeJS - 多次等待调用以顺序构建输出对象
- json - 如何转换 TSV 表中的树结构
- java - How to make multi thread with SwingWorker?