Back to Forum
Canvas (flying balls)
MammaMia posted 7 years ago

Hi Chris!

With your tutorial about canvas setup, i made that "game" where balls are flying and if the mouseX and mouseY < 50 .... , then the balls scales, else scales down.

I'm trying to center the canvas (in the middle of page), but the balls scales event if mouse is 200px higher, than balls.

Please help. ;)

chris's profile photo
chris posted 7 years ago

Hi!

You may need to take the canvas's offset into account, IE, where is the canvas in relation to the page. If the canvas is not full width and centered using CSS margin and padding, you can get its offset with:

const offsetLeft = document.querySelector('canvas').getBoundingClientRect().left
const offsetTop = document.querySelector('canvas').getBoundingClientRect().top

Add offsetLeft onto your mouse's x coordinate within your event listener, then offsetTop onto its y coordinate.

Your balls should scale as expected without any issues in regards to their positioning.

M
MammaMia posted 7 years ago

Hi, thanks.

But could you please write CSS part to center te canvas using margin and padding;

Maybe my is good well ?

    canvas
    {
        background: rgb(28, 3, 68);
        position:absolute;
        top:0;
        bottom:0;
        right:0;
        left:0;
        margin:auto;
    }
    body{
        margin:0;

    }

chris's profile photo
chris posted 7 years ago

Should be able to get the canvas perfectly centered w/ CSS using:

canvas {
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
}

I typically make my canvas fullscreen with JavaScript however. That code would look like this:

canvas.width = innerWidth
canvas.height = innerHeight

Want to participate?

Create a free Chris Courses account to begin

Providing the lift to launch your development career

© 2026 Chris Courses. All rights reserved.