Steven_Harris_
Steven_Harris_

Reputation: 1121

HTML5 canvas game won't work when applying margins to canvas

I've been playing around with the following game.

I want to add margin: 0 auto but when I apply any kind of margin, padding etc the game stops working.

In this example i've added margin: 200px; and you'll notice the game doesn't work.

Not certain as to why.

Upvotes: 0

Views: 45

Answers (2)

Michael Schneider
Michael Schneider

Reputation: 506

With moving the whole canvas of 200px, you need to make sure that the mousetracking is correct.

You can simply get your goal by change a function:

function trackPosition(e) {
    mouse.x = (e.pageX-200);
    mouse.y = e.pageY;
}

We set mouse.x with -200px which is used as margin.

You need also to change your 'button' click event:

// Variables for storing mouse position on click
var mx = (e.pageX-200),
my = e.pageY;

Upvotes: 1

Patrick Evans
Patrick Evans

Reputation: 42736

Because you move the canvas, the hit detection code is off because it uses the pageX,pageY values which are values relative to the page. You can get positions relative to the canvas itself by using the offsetX,offsetY values which should get you better hit detection without have to do extra calculations

function btnClick(e) {
    // Variables for storing mouse position on click
    var mx = e.offsetX,
    my = e.offsetY;

You may need to do this in other parts of the code as well, and/or other calculations to make sure the hit detection is correct

Upvotes: 1

Related Questions