1

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!

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the swift reply, though I cant quite seem to get it to work. Im probably being really blonde.. Either way The div Im trying to add it to is called "gameCanvas", the code I posted is from a testing file to see why it wasnt working..
Are you getting any errors now? Can you try using document.getElementById('gameCanvas') instead of document.body.childNodes[0]? If it's still not working it would be helpful if you could provide a jsfiddle showcasing the problem.
jsfiddle.net/2t0685ts Take a look at that, Its probably something really simple, Im new to JS to dont be too harsh on me!
Absolute diamond!! Thank you so much!
Thanks for taking the pain, connorrickk and @Bastiaanus

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.