CHANNELS:

All
M
Canvas (flying balls)
Canvas
MammaMia posted 2 months 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 posted 2 months 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.

1
M
MammaMia posted 2 months 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;

    }

0
chris posted 2 months 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
0

Want to participate?

Create a free Chris Courses account to begin

or
Sign In
Cheat Sheet Preview

Download The Official Chris Courses HTML5 Canvas Cheat Sheet

Essential canvas syntax at your fingertips.

Download Cheat Sheet

Providing the lift to launch your development career

© 2020 Chris Courses. All rights reserved.