Reputation: 640
I'm trying to make a JavaScript game using p5. I need an image as the background, however it is not displaying. I've put the absolute path for the image and I'm running a server using vs code liver server.
sketch.js
var backgroungImg;
function preload() {
backgroundImg = loadImage(
"C:/full path/img/extra/map1.png"
);
}
function setup() {
createCanvas(1000, 600);
background(backgroundImg);
}
function draw() {}
index.html
<html>
<head>
<script src="p5.min.js"></script>
<script src="C:/full path/src/sketch.js"></script>
</head>
<body>
<main>
</main>
</body
Upvotes: 1
Views: 487
Reputation: 36436
@rishi found the answer. As we suspected it has to be an http/s call. He reports that using:
http://127.0.0.1:8080/img/extra/map1.png
solved the problem (the IP address would of course need checking for an installation).
For the record and in case anyone else lands here, here is the initial thinking:
This looks like a CORS (Cross-origin Resource Sharing) problem - your code not being allowed to load a local file. You need to use the http/https protocol, for example by removing the full path and using src/sketch.js or whatever is relevant for your file structure on your local server.
I do not have a local server but I tested on a remote one, trying to load a file from a different origin and got the problem. If I put the background image file into the same system it works OK. You can see it on https://rgspaces.org.uk/bayeuxtapestry/p5test.html
Here's the code I used:
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.js"></script>
<script src="assets/sketch.js"></script>
</head>
<body>
<main>
</main>
</body>
</html>
and in assets/sketch.js I have
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() {
}
There is some discussion on this issue and it sounds as though it is possible to install a local proxy which gets round the CORS problem. See for example Deadly CORS when http://localhost is the origin
Upvotes: 2