1

I have a Sketch in Processing written in P5.js, but I don't know how to implement user's input. The program needs to get .jpg image and it's working on it. Every my attempt of user-input implementation ends with blank screen or endless "Loading..." screen. Below is example with preloaded image (I need user to do it).

let img;
let size;
let pixels = [];

function preload(){
  img=loadImage('image.jpg');  
}

function setup() {
  img.resize(windowHeight,0);
  size = img.height/2;
  createCanvas(img.width, img.height);
  background(0);
  makePixels();
  drawPortrait();
}
function makePixels(){
    for(let y=0; y<height; y+=size){
      for(let x=0; x<width; x+=size){
        let c = img.get(x,y);
        tint(c);
        pixels.push ( new Pixel (x,y,size,c) );
      }
    }
}

function drawPortrait(){
  for(let p of pixels){
    p.show();
  }
}

function drawLastFour(){
  for(let i = pixels.length-4; i<pixels.length; i++){
    pixels[i].show();
  }
}

function mouseMoved(){
  for(let i = 0; i<pixels.length; i++){
      if( (mouseX > pixels[i].x) && (mouseX <= pixels[i].x+pixels[i].s) && (mouseY > pixels[i].y) && (mouseY <= pixels[i].y+pixels[i].s) ){
        for(let py = pixels[i].y; py<pixels[i].y+pixels[i].s; py+=pixels[i].s/2){
          for(let px = pixels[i].x; px<pixels[i].x+pixels[i].s; px+=pixels[i].s/2){
            let c = img.get(px, py);
            pixels.push( new Pixel(px,py,pixels[i].s/2, c) );
          }
        }
        pixels.splice(i,1);
        break;
      }
    }
  drawLastFour();
}

1 Answer 1

2

You can use the createFileInput function to create an input element of type file. Your user can then select an image file, which can be used by your sketch. Here is the (slightly modified) example code that shows how you can use it:

let inputElement;
let userImage;

function setup() {
  inputElement = createFileInput(handleFile);
  inputElement.position(0, 0);
}

function draw() {
  background(255);

  if (userImage != null) {
    image(userImage, 0, 0, width, height);
  }
}

function handleFile(file) {
  print(file);

  if (file.type === 'image') {
    userImage = createImg(file.data, '');
    userImage.hide();
  } else {
    userImage = null;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.