0
HTMLキャンバスを使用して描画し、画面全体に赤い四角形を移動しています。しかし、私が四角形のx値を変更してそれを再描画すると、 "mg_player1が定義されていません..."というエラーがスローされます。コード内の問題を理解できないようです。あなたがグローバルにmg_player1
オブジェクトを定義する必要がHTMLキャンバスでオブジェクトを再描画する際の問題
<html>
<head>
<style>
#mg_canvas {
\t padding-left: 0;
padding-right: 0;
margin-left: auto;
margin-right: auto;
display: block;
\t width: 1600px;
\t height: 800px;
\t border: 4px solid black;
}
</style>
<body onload="mg_start()">
<div class="hideMultiGames">
<button class="button" onclick="mg_player1.moveUp()">Click me!</button>
<script>
\t function mg_start() {
\t \t multiGames_area.drawCanvas();
\t \t var mg_player1 = new mg_player("red", 0, 670);
\t }
\t var multiGames_area = {
\t \t canvas : document.createElement("canvas"),
\t \t drawCanvas : function() {
\t \t \t if (document.getElementById("mg_canvas")) {
\t \t \t }
\t \t \t else {
\t \t \t \t this.canvas.width = 1600;
\t \t \t \t this.canvas.height = 800;
\t \t \t \t this.canvas.id = "mg_canvas"
\t \t \t \t this.canvas.className = "hideMultiGames";
\t \t \t \t multiGames_area.context = this.canvas.getContext("2d");
\t \t \t \t document.body.insertBefore(this.canvas, document.body.childNodes[0]);
\t \t \t \t
\t \t \t }
\t \t },
\t \t mg_drawGround : function() {
\t \t \t var mg_ground;
\t \t \t mg_ground = document.getElementById("mg_canvas");
\t \t \t var ground = mg_ground.getContext("2d");
\t \t \t ground.moveTo(0,700);
\t \t \t ground.lineTo(1600,700);
\t \t \t ground.stroke();
\t \t },
\t \t mg_clear : function() {
\t \t \t this.context.clearRect(0, 0, 1600, 800);
\t \t },
\t }
\t function mg_player(color, x, y) { //stores general shared methods and properties of players
\t \t this.width = 30;
\t \t this.height = 30;
\t \t this.color = color;
\t \t this.x = x;
\t \t this.y = y;
\t \t ctx = multiGames_area.context;
\t \t ctx.fillStyle = this.color;
\t \t ctx.fillRect(this.x, this.y, this.width, this.height);
\t \t this.moveUp = function() { //function that is throwing errors
\t \t \t this.x = 1000;
\t \t \t ctx.fillStyle = this.color;
\t \t \t ctx.fillRect(this.x, this.y, this.width, this.height);
\t \t };
\t }
\t
</script>
</div>
</body>
</html>
`
あなたはグローバルmg_player1' '定義されたことはありませんので。 – dfsq