无法显示p5 JavaScript背景图片

时间:2020-09-13 09:57:46

标签: javascript p5.js

我正在尝试使用p5制作JavaScript游戏。我需要一个图像作为背景,但是没有显示。我已经为图像设置了绝对路径,并且正在使用vs代码肝脏服务器运行服务器。

sketch.js

.thp-close:before, 
.thp-close:after {
    background-color: #f4c001;
}

index.html

var backgroungImg;

function preload() {
  backgroundImg = loadImage(
    "C:/full path/img/extra/map1.png"
  );
}

function setup() {
  createCanvas(1000, 600);
  background(backgroundImg);
}

function draw() {}

1 个答案:

答案 0 :(得分:2)

@rishi找到了答案。我们怀疑这一定是http / s调用。他报告说使用:

http://127.0.0.1:8080/img/extra/map1.png

解决了这个问题(IP地址当然需要检查安装)。

记录下来,以防万一其他人落在这里,这是最初的想法:

这看起来像是CORS(跨域资源共享)问题-您的代码无法加载本地文件。您需要使用http / https协议,例如,删除完整路径并使用src / sketch.js或与本地服务器上的文件结构相关的任何东西。

我没有本地服务器,但是我在远程服务器上进行了测试,试图从其他来源加载文件并出现问题。如果我将背景图像文件放入同一系统,则可以。您可以在https://rgspaces.org.uk/bayeuxtapestry/p5test.html

上看到它

这是我使用的代码:

<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/p5@1.1.9/lib/p5.js"></script>
    <script src="assets/sketch.js"></script>
  </head>
  <body>
    <main>
    </main>
  </body>
</html>

以及我拥有的assets / sketch.js中

var backgroundImg;

function preload() {
  backgroundImg = loadImage("boat-and-horses-768x546.png");//this file is in the same folder
}

function setup() {
  createCanvas(1000, 600);
  background(backgroundImg);
}

function draw() {
}

对此问题进行了一些讨论,听起来好像可以安装解决CORS问题的本地代理。例如参见Deadly CORS when http://localhost is the origin