react-p5 icon indicating copy to clipboard operation
react-p5 copied to clipboard

Is it possible to change the image displayed with React image upload?

Open nijatmursali opened this issue 2 years ago • 1 comments

Hello,

Currently, I'm working on one project and I need to read the image from input and show it in p5 canvas. I'm trying it now, but it does not draw the image on canvas. What could be the reason?

Code:

const [selectedFile, setSelectedFile] = useState();
 let backgroundImage;
 let dragging = false; // Is the object being dragged?
 let rollover = false; // Is the mouse over the ellipse?

 let x, y, w, h; // Location and size
 let offsetX, offsetY; // Mouseclick offset

const setup = (p5, parentRef) => {
   p5.createCanvas(1000, 500).parent(parentRef);
   // Starting location
   x = 100;
   y = 100;

   // Dimensions
   w = 300;
   h = 400;
   const url =
     "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/640px-Image_created_with_a_mobile_phone.png";
   backgroundImage = p5.loadImage(url);
 };

 const draw = (p5) => {
   p5.background(233);

   if (
     p5.mouseX > x &&
     p5.mouseX < x + w &&
     p5.mouseY > y &&
     p5.mouseY < y + h
   ) {
     rollover = true;
   } else {
     rollover = false;
   }

   // Adjust location if being dragged
   if (dragging) {
     x = p5.mouseX + offsetX;
     y = p5.mouseY + offsetY;
   }

   if (selectedFile != null) {
     const url = URL.createObjectURL(selectedFile);
     backgroundImage = p5.loadImage(url);
   } else {
   }
   p5.image(backgroundImage, x, y, w, h);
   p5.noFill();
   p5.rect(400, 100, 200, 300);
 };

 const mousePressed = (p5) => {
   if (
     p5.mouseX > x &&
     p5.mouseX < x + w &&
     p5.mouseY > y &&
     p5.mouseY < y + h
   ) {
     dragging = true;

     offsetX = x - p5.mouseX;
     offsetY = y - p5.mouseY;
   }
 };

 const mouseReleased = (p5) => {
   // Quit dragging
   dragging = false;
 };

On React return I just have:

 <div>
        <h1>Select an image</h1>
        <input
          type="file"
          name="file"
          id="file"
          // onChange={(e) => setSelectedFile(e.target.files[0])}
          onChange={(e) => {
            setSelectedFile(e.target.files[0]);
            handleFileInput(e);
          }}
        />

nijatmursali avatar Jul 20 '22 14:07 nijatmursali

I didn't get any response to this..

nijatmursali avatar Jul 25 '22 13:07 nijatmursali

Could you produce a sample repo?

kyeshmz avatar Oct 14 '22 04:10 kyeshmz