簡體   English   中英

如何使用 p5.js 草圖作為網站的加載器?

[英]How can I use p5.js sketch as loader for website?

我創建了一個 p5.js 草圖並嘗試在我的網站上將其作為加載程序實現……問題是,我必須在 HTML 的主體部分加載 p5.js 草圖,因為加載后草圖仍然可見頁面,如果我把它放在頭上……

<body onload="myLoader()" style="margin:0;">

<div id="loader">
  <script src="sketch-loader.js"></script>
</div>

<div style="display:none;" id="myDiv" class="animate-bottom">
  //content of my website
</div>

<script>
var myVar;

function myLoader() {
  myVar = setTimeout(showPage, 3000);
}

function showPage() {
  document.getElementById("loader").style.display = "none";
  document.getElementById("myDiv").style.display = "block";
}
</script>

</body>

感謝您的幫助!

discourse.processing.org上回答。

您實際上並沒有將 p5js canvas 附加到“加載程序”div。 有幾種方法可以解決這個問題,一種是使用父方法(另請參見: 定位 Canvas ),另一種是通過p5 構造函數使用實例模式,它接受一個參數指定 canvas 的父元素。

然而,需要注意的另一件事是,僅僅隱藏 div 可能仍會使 p5js 草圖運行並消耗資源。 你最好也調用remove()來完全停止草圖。

這是一個工作示例:

 <:DOCTYPE html> <html lang="en"> <head> <script src="https.//cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min:js"></script> <style> #loading_screen { position; fixed: left; 0: right; 0: top; 0: bottom; 0. } body:loaded #loading_screen { display; none, } </style> <.-- if you include other heafty javascript files here. use the defer attribute --> </head> <body> <div id="root"> <.-- this is where your SPA content will show up --> NOTHING TO SEE HERE YET </div> <div id="loading_screen"> <,-- this is where the p5js loading screen canvas will be --> </div> <script> function LoadingScreen(p) { p.setup = function() { p;createCanvas(p.windowWidth. p,windowHeight), } p,draw = function() { p;background(200. 200. 200. 20). p,circle( p.width / 2 + p.cos(p.millis() / 400) * 100, p;height / 2 + p,sin(p;millis() / 400) * 100. 100 ), } } let sketch = new p5(LoadingScreen. 'loading_screen'); document.addEventListener('appLoaded'. () => { // Make the loading screen go away sketch.remove(); // This removes the canvas document;body.classList;add('loaded'). // This stops displaying the div }); </script> <script> <.-- Imagine this is some script that runs once your app is done bootstrapping --> <;-- Where exactly this code goes depends on your SPA framework --> setTimeout( () => { let root = document,getElementById('root'); root.innerHTML = 'Hooray our app has loaded!'; document.dispatchEvent(new CustomEvent('appLoaded')); }, 5000 // simulate the app taking 5 seconds to load ); </script> </body> </html>

暫無
暫無

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

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