1

I'm trying to write a small piece of javascript (p5.js) so I can drag in an image from my desktop into the browser. Then using my mouse cursor X&Y I can distort the image. I had this code working previously by just simply loading the image, but now I wish to have some interactive element with it so the user can load any image they want and apply the same effect.

var c;
var slice;
var sliceCount;
var sliceWidth;
var sliceWidthChecker;

function setup(){
var c = createCanvas(500,500);
background(51);
fill(255);
c.drop(gotFile);
}

function dropped() {
background(0);
}

function gotFile(file){
var img = createImg(file.data).hide();
image(img, 0, 0, 500, 500);
console.log(img)
noStroke();
stroke(0);
fill(255);
text(file.name, 20, 60);
text(file.size+' bytes', 20, 110);
}

function draw(){
/* setting the sliceWidth */
sliceWidth=windowWidth/12;

/* setting the how many slice on the canvas depending on the sliceWidth
*/
var maxSliceCount = windowWidth/sliceWidth;

/* this is trying to control, if the get pixel reads beyond the image,    
it goes back, but didn't work.*/
if (sliceWidth >= c.width) {
 sliceWidthChecker = sliceWidth - c.width;
 } else {
   sliceWidthChecker = sliceWidth;
 }        

/* drawing the slices */ 
for (sliceCount = 0; sliceCount < maxSliceCount; sliceCount++) {
/* sliceWidthChecker is trying to fix if get pixel reads beyond the        
image, didn't work, can be replace by simply "sliceWidth" */   
/* *0.5 after mouseX is to help if the mose move too much */
slice = c.get(mouseX*0.5+sliceCount*40, 0, sliceWidthChecker,    
c.height);
image(slice, sliceWidth*sliceCount, windowHeight/10, slice.width,     
slice.height);
}
}
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
James Aspey
  • 11
  • 1
  • 1
  • 3

1 Answers1

1

You're declaring a variable c at the top of your sketch:

var c;

Then you're redeclaring a new variable that happens to have the same name inside your setup() function:

var c = createCanvas(500,500);

Because of the var keyword here, this is a different variable then the one you created above!

Then later, you use the original c variable:

if (sliceWidth >= c.width) {

But note that the original c variable has never been given a value. That's what's causing your error.

To fix this error you can simply remove the var keyword when you initialize the second c variable:

c = createCanvas(500,500);

This code sets the original c variable to the canvas value.

After this you have other errors in your code, but this should get you over this hurdle.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107