Astro网站集成p5.js:代码运行但无画布生成的问题求助
问题:Astro中p5.js无法生成画布但代码已执行?
我在用Astro开发个人网站,部分模块需要运行p5.js草图。已经给p5.js和草图添加了<script>标签,但页面运行时p5.js似乎未生效——DOM中没有生成画布,控制台也无任何报错。我已在草图中添加console.log确认代码已执行;无论是将p5.js下载至本地Public文件夹,通过<script is:inline src="/p5.js"></script>引入,还是通过CDN引入,均能验证p5.js已加载,但问题仍未解决。
最小复现代码
以下是pages文件夹中的Astro页面示例:
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>min p5js with astro example</title> <!-- Import p5.js. First way is directly from the downloaded source in /public. Second way is from the CDN --> <!-- <script is:inline src="/p5.js"></script> --> <script is:inline src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script> <script> console.log("Running script...") function setup() { createCanvas(400, 400); background(0); } function draw() { fill(255); ellipse(mouseX, mouseY, 80, 80); } </script> </head> <body> </body> </html>
已尝试的解决方案
- 从CDN及本地文件两种方式引入p5.js
- 引入p5.js压缩版本,无改善
- 将草图代码直接写在
<script>标签内 - 将草图代码单独放在js文件中,通过
import引入 - 添加
console.log确认JavaScript代码已运行
内容的提问来源于stack exchange,提问作者Peter Marsh
相关产品推荐
相关产品推荐

