簡體   English   中英

如何在JavaScript中相對於窗口大小在屏幕上居中顯示項目?

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

這是我的代碼,可以更好地解釋我要做什么。 它接近居中,但始終偏離中心一點。 它在10,000 x 10,000像素的畫布上。

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

起初,我認為偏移量是由於滾動條引起的,但是即使我不隱藏滾動條,圓也離屏幕中心還有一點距離。 任何幫助使它居中正確將不勝感激。 有時在屏幕上只顯示一半或四分之一的圓,這似乎是隨機的,但大多數情況下它接近中心。

似乎在window.scrollTo添加了一個小的填充
我還沒有看過任何文檔詳細說明此問題,老實說,直到現在我還沒有注意到,填充很小(〜5像素),因此我嘗試將小圓圈放在左上角,圓心應該在給定的右邊協調但不完全一致,當我們只應看到整個圓圈的四分之一時,我們可以看到整個圓圈。

這是顯示問題的一個小樣本:

 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> 

由於您使用的是大畫布,因此我建議您嘗試使用JS游戲引擎:
https://github.com/collections/javascript-game-engines

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM