首页 > 解决方案 > 用 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>

代码的输出是这样的:

在此处输入图像描述

在这一点上,我不再确定问题是哪个字符变量,因此字符没有被显示,或者与画布有关,因为画布的尺寸不正确,我不完全确定为什么画布会改变尺寸(如果屏幕上显示的矩形是画布)。这就是我所说的代码破坏的意思。

标签: javascripthtmlcanvas

解决方案


对象中有一些语法错误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>

这是否解决了您的问题,或者您是否期望发生其他事情?


推荐阅读