Canvas.elt.toDataURL saving blank images

This is my nextjs (reactjs) code, I’m using the p5 library, everything is fine until I try to view the saved base64 image, the image is saved as blank. Any idea what I might be doing wrong? or is it a bug in the p5 reactjs library?


//import { useState } from 'react';

const Sketch = (W, H, saveDataURI) => (p) => {

  const BRUSH_START_SIZE = 10;

  const BRUSH_END_SIZE = 60;

  const BRUSH_DELTA = 1;

  let dataURI;

  let canvas;

  let count = BRUSH_START_SIZE;

  let bg;

  let button;

  let mouseWasPressed = false;

  function clearCanvas() {

    p.clear();

  }

  p.setup = () => {

    p.createCanvas(W, H);

    bg = p.loadImage("/foot_scan_clean_estiqama.png");

    canvas = p.select("canvas");

    saveDataURI(canvas.elt.toDataURL());

  };

  p.draw = () => {

    p.background(bg);

    if (p.mouseIsPressed) {

      if (count < BRUSH_END_SIZE) count = count + BRUSH_DELTA;

      else count = BRUSH_END_SIZE;

      let squareColor = p.color(255 - count, 0, 0);

      squareColor.setAlpha(20);

      p.fill(squareColor);

      p.noStroke();

      p.ellipse(p.mouseX, p.mouseY, count, count);

      mouseWasPressed = true;

      dataURI = canvas.elt.toDataURL("image/png");

    } else {

      if (mouseWasPressed) {

        p.updatePixels();

       // console.log(canvas);

        console.log(dataURI);

        saveDataURI(dataURI);

        mouseWasPressed = false;

      }

      count = BRUSH_START_SIZE;

    }

  };

  p.mouseDragged = () => {

    count = BRUSH_START_SIZE;

    // prevent default

    return false;

  };

};

export default Sketch;

this simple code works for me

let c;
function setup() {
  c = createCanvas(400, 400);
}

function draw() {
  background(220);
  console.log(c.elt.toDataURL("image/png"));

  noLoop();
}

maybe your select is pointing to another DOM?

Also please link to questions you opened in other forums

1 Like