How do I center an item on the screen in relation to the window size in javascript?

104 views Asked by At

Here is my code to better explain what I'm trying to do. It's close to getting it centered but it's always a little off from center. It's on a 10,000 by 10,000 pixel canvas.

var winX=window.innerWidth/2; //get the clients browser width
var winY=window.innerHeight/2; //get the clients browser height
function drawPlayer() {
        ctx.beginPath();
        player.pX=randInt(4,10004); //get random X coordinate
        player.pY=randInt(4,10004); //get random Y coordinate
        ctx.arc(player.pX, player.pY, circR, 0, 2*Math.PI); //creates the circle that i'm trying to center on the screen
        ctx.fillStyle=colors[randInt(0,6)];
        ctx.fill();
        ctx.closePath();
        window.scrollTo((player.pX-winX)-2, (player.pY-winY)-2);
        document.body.style.overflow='hidden';
}

At first I thought the offset was because of the scrollbars, but even when I don't hide the scrollbars the circle is still a little bit off from the center of the screen. Any help on getting it centered right would be greatly appreciated. Also sometimes only half of the circle or a quarter of it is shown on the screen, it seems to be kind of random but most of the time it's close to center.

1

There are 1 answers

0
Helder Sepulveda On

There seems to be a small padding added to the window.scrollTo
I have not seen any documentation detailing this issue, and honestly I've never noticed until now, the padding is small (~5px) so I tried putting small circles on the top left, the center of the circle should be right on the given coordinated but is not quite there, we can see the whole circle when we should be seen only a quarter of it...

Here is a small sample showing the issue:

document.body.style.overflow = 'hidden';

ctx = document.getElementById('c').getContext('2d');
ctx.beginPath();
for (var i = 0; i < 10; i++ )
  ctx.arc(500 + i*20, 500 + i*20, 5, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill();

var n = 500
function scroll() {
  n = (n == 600) ? 500 : 600;
  window.scrollTo({top: n, left: n, behavior: "smooth" });
}

setInterval(scroll, 1000);
scroll()
<canvas id="c" height=10000 width=10000></canvas>

Since you are using such a large canvas, I would recommend you to try a JS game engine:
https://github.com/collections/javascript-game-engines