Bob Timmon
Bob Timmon

Reputation: 101

Upload Image to Canvas p5js

I am a beginner at p5js, and I was learning how to upload an image. This is my code:

PImage img;

function setup() {
  size(1400, 1400)
  img = loadImage("india-map.gif");
}


function draw() {
  background(0)
  image(img, 100, 100);
}

When I run it, it says that there is a problem with line 1. The error message reads:

SyntaxError: Expected ;but found img.

I don't know what this means and what I should do. Can anyone help me?

Edit:

I changed the code to

var image1;


function preload(){
 image1= loadImage("india-map.jpg");
}

function setup(){
  
 creatCanvas(1350,600) 
}

function draw(){
image(image1, 100, 100); 
  
}

My page just says ...loading without loading any image.

Upvotes: 3

Views: 1969

Answers (2)

Nick Parsons
Nick Parsons

Reputation: 50674

In addition to kemicofa great answer, I think it is also important to note the loadImage is asynchronous. This means that when we call loadImage it will take some time for the method to retrieve and load the image data into memory. As a result of this, loadImage doesn't happen instantly like the rest of your code.

Thus, while your image is being loaded, the rest of your code is still able to run, including the draw method. This means that if your draw method only runs once (you can make it run only once by using noLoop(), your image will not be displayed because it hasn't yet been loaded in.

There are a couple of solutions to this issue such as using a callback. However, p5js offers another method which runs before setup called preload. In this function, you can load your image to make sure that it is ready for setup and draw to use.

Using all these ideas you will end up with code which looks somewhat like:

let img;

function preload() {
  img = loadImage('india-map.gif'); // load media and other data
}

function setup() { // only executed once preload is has finished loading data
  createCanvas(400, 400);

}

function draw() { // only executed once preload is has finished loading data
  image(img, 0, 0, width, height);
  noLoop(); // stop draw from looping (to show img has been loaded)
}

You can find a working example here

Upvotes: 1

kockburn
kockburn

Reputation: 17616

Explanation:

PImage is a type coming from the Processing3 library.

In javascript, when declaring a variable use const, let or var.

Additionally, the size method comes from Processing3 as well. Instead use createCanvas method and pass the size as a parameter.

Go over the documentation and make sure the methods you wish to use exist.

Solution:

let img;
function setup() {
  createCanvas(100, 50);
  img = loadImage("india-map.gif");
}


function draw() {
  background(0);
  image(img, 100, 100);
}

Upvotes: 0

Related Questions