1

I have been trying to implement a load canvas function using the drag and drop method explained in the P5 reference below. However on the first instance of dragging an image to the canvas, the image will not load. The second attempt will load the image fine. This happens with every 'new' image that I try to load to the canvas.

https://p5js.org/examples/dom-drop.html

When commenting out the '.hide' you can see that the image data is successfully loading on the first attempt. I am a little confused as to how I correct this issue.

Thank you to anyone that can point me in the right direction.

index.html

<!DOCTYPE html>
<html>
  <head>    
      <script src="p5.js"></script>
      <script src="p5.dom.js"></script>
    <script src="sketch.js"></script>

  </head>
  <body>
  </body>
</html>

sketch.js

function setup() {
  // create canvas
  var c = createCanvas(710, 400);
  background(100);
  // Add an event for when a file is dropped onto the canvas
  c.drop(gotFile);
}

function draw() {
  fill(255);
  noStroke();
  textSize(24);
  textAlign(CENTER);
  text('Drag an image file onto the canvas.', width/2, height/2);
  noLoop();
}

function gotFile(file) {
  // If it's an image file
  if (file.type === 'image') {
    // Create an image DOM element but don't show it
    var img = createImg(file.data).hide();
    // Draw the image onto the canvas
    image(img, 0, 0, width, height);
  } else {
    println('Not an image file!');
  }
}
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
David
  • 27
  • 4

1 Answers1

0

My guess is that this line takes some time to process the image in the background:

 var img = createImg(file.data).hide();

So when you immediately try to use img, it's not always done processing.

image(img, 0, 0, width, height);

One workaround for this is to not use the img right away. Here's a simple example:

var img;

function setup() {
  var c = createCanvas(710, 400);
  c.drop(gotFile);
}

function draw() {
  if(img){
    image(img, 0, 0, width, height);
  }
}

function gotFile(file) {
  if (file.type === 'image') {
    img = createImg(file.data).hide();
  }
}
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
  • This fix works, however, Is there another way that does not use the draw loop ? Once the image has loaded you can no longer manipulate the canvas.The image is being constantly loaded with each new frame. – David Mar 25 '18 at 17:30
  • The image is not constantly loaded with each frame. It's loaded once in the `gotFile()` function. Why can you not manipulate the canvas? What are you trying to do? Consider posting a new question with an updated [mcve]. – Kevin Workman Mar 25 '18 at 17:42
  • Its part of a larger piece of work i will try and condense the example into a new question. Thank you – David Mar 25 '18 at 18:09