connorrickk
connorrickk

Reputation: 13

Problems with HTML canvas?

Okay, So I'm following a tutorial from W3Schools and Im trying to place this canvas inside a div. Problem is, it keeps going back to the start of body? Ive tried changing some of the code but I just cant get it right! Any chance someone could shed some light? Im trying to put it in a div called "gameCanvas" but ive pasted the code that works.

var myGamePiece;
var myObstacles = [];
var myScore;

function startGame() {
    myGamePiece = new component(30, 30, "red", 10, 120);
    myScore = new component("30px", "Consolas", "black", 280, 40, "text");
myGameArea.start();
}

 var myGameArea = {
    canvas : document.createElement("canvas"),
start : function() {
    this.canvas.width = 480;
    this.canvas.height = 270;
    this.context = this.canvas.getContext("2d");
    document.body.insertBefore(this.canvas, document.body.childNodes[0]);
    this.frameNo = 0;
    this.interval = setInterval(updateGameArea, 20);
    },
clear : function() {
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function() {
    clearInterval(this.interval);
}
}

Thanks in Advance!

Upvotes: 1

Views: 464

Answers (1)

Bastiaanus
Bastiaanus

Reputation: 357

Is document.body.childNodes[0] the div you are trying to wrap the canvas in?

You are currently inserting your canvas before the div (insertBefore) instead of inside it. You can use document.body.childNodes[0].appendChild(this.canvas) to add the canvas as a child to the div.

Edit:

Knowing that the div you are trying to append to has the id gameCanvas the following should work:

Replace document.body.insertBefore(this.canvas, document.body.childNodes[0]) in your original code with document.getElementById('gameCanvas').appendChild(this.canvas).

Upvotes: 3

Related Questions