Resizing P5 Canvas according to image size

Please take a look at the following P5 code. The point of this small app is to drag and drop an image on the canvas changing its size according to the "uploaded" image's width and height.

/**************************************************/
//GENERAL
var canvas;

//IMAGE
var img;//image
var imgW;//image width
var imgH;//image height
/**************************************************/
function setup(){
  canvas = createCanvas(710, 400);//initial canvas size
  canvas.drop(gotFile);
}
/**************************************************/
function draw(){
    background(0);
    if(img){
    image(img, 0, 0);
    imgW = img.width;
    imgH = img.height;
        if(imgW > 0 && imgH > 0){
            resizeCanvas(imgW, imgH);
        }
    }
    fill(255);
    text(imgW + ", " + imgH, 10, 10);
}
/**************************************************/
//
function gotFile(file){
  if (file.type === 'image') {
    img = createImg(file.data).hide();
  }
}
/**************************************************/
function mouseClicked(){
    if(img){
        if(imgW > 0 && imgH > 0){
            resizeCanvas(imgW, imgH);
        }
    }
}

Using draw(): Once the image has been loaded successfully (at least displaying it), I assign its width and height to the variables imgW and imgH. Followed by the canvas size change... which leads to an error, the canvas' size the same as the uploaded image (checked on Developer Tools) but doesn't display anything.

Using mouseClicked(): When disabling the canvas size change on draw(), and click on the canvas, the resize happens perfectly showing the image.

The application needs to work without clicking, it should be automatic change (canvas size) after dropping the image.

UPDATE This is what I see on the console when dropping the The error I get on the console:

Uncaught RangeError: Maximum call stack size exceeded
    at Array.map (<anonymous>)
    at p5.Color._parseInputs (p5.js:44096)
    at new p5.Color (p5.js:43147)
    at p5.color (p5.js:42827)
    at p5.Renderer2D.background (p5.js:50315)
    at p5.background (p5.js:44288)
    at draw (sketch.js:21)
    at p5.redraw (p5.js:52435)
    at p5.resizeCanvas (p5.js:51826)
    at draw (sketch.js:30)

Answers

Sign In or Register to comment.