Search code examples
javascriptfilereaderreact-konvakonva

Uncaught TypeError: getImage.crop is not a function


The code I get this error is:

const crop = imageSrc.crop({
  x: value.x / ratio_w,
  y: value.y / ratio_h,
  width: value.width / ratio_w,
  height: value.height / ratio_h,
});

I got this error when I was trying to get a subimage with the x,y, width and height coordinates of the image area to get. In there I declare

const [imageSrc, setImageSrc] = useState(null)

and I update the value of imageSrc here:

const handleImageChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onloadend = () => {
      setImageSrc(reader.result);
    };
    reader.readAsDataURL(file);
  }
};

According to Konva's documentation, there are instructions:

// get crop
var crop = image.crop();

I asked in repo of konva but no one respond my question.


Solution

  • From the documentation for FileReader: readDataAsURL()...

    the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string.

    This is a string, not a Konva.Image.

    You will need to load the result using something like Konva.Image.fromURL() before you can use methods like crop()

    reader.onloadend = () => {
      Konva.Image.fromURL(reader.result, setImageSrc, console.error);
    };