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.
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;
}
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