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.
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:
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