Jack Browne
Jack Browne

Reputation: 13

p5.js image in a buffer

I am trying to load image "image.png" and place it in the preaviously created createGraphics() buffer. However when I load the buffer in draw() the image is not there. I am wondering if an image can be loaded into a buffer, and if so how ?

var buffer;
var image;

function setup() {
    createCanvas(800, 800);
    image = loadImage("image.png");
    buffer = createGraphics(800, 800);
    buffer.background(255, 255, 0);
    buffer.image(image, 0, 0)
}

function draw() {
    image(buffer, 0, 0);
}

any help would be greatly appreciated.

Upvotes: 1

Views: 1272

Answers (1)

Malte
Malte

Reputation: 556

  1. It is not good to call your variable image as p5.js already has an image() function (which you use).

  2. Use preload() to load the image. This ensures that the image is actually loaded before you try to load it in your buffer within setup(). See here for more info on this.

A working example is given here. It uses the following p5 code.

var buffer;
var img;

function preload() {
  img = loadImage("p5im.png");
}

function setup() {
  createCanvas(600, 600);
  
  buffer = createGraphics(400, 400);
  buffer.background(255, 255, 0);
  buffer.image(img, 0, 0)
}

function draw() {
  image(buffer, 0, 0);
}

Upvotes: 1

Related Questions