Creating Moralis Files from a canvas

I am trying to create a Moralis file from an html canvas element and keep getting the error
TypeError: Cannot create a Parse.File with that data.

var canvasElement = cropper.getCroppedCanvas();
var ourBlob = canvasElement.toBlob(function(blob) {
var url = URL.createObjectURL(blob);
var filename = document.getElementById(“name”).value + “.png”;
const imageFile = new Moralis.File(filename, url);
});

Have also tried with canvasElement.toDataURL(“image/png”); … same problem

1 Like

Hey @kastech, hope you are well.

I think you need to restructure the way your getting the canvas data, saving the file in moralis should be the last step once your sure the data from canvas is correct. So for that you might need a buffer to convert the canvas data properly.

I’m no canva expert but long ago i was able to create draws with canvas, and save it to moralis.

  const getImageData = () => {
// reference element of canvas
    const canvasEl = elementRef.current;
// get the DataUrl from canvas element
    let dataUrl = canvasEl.toDataURL("image/png");
// create the buffer for canvas object
    const buffer = Buffer(dataUrl.split(",")[1], "base64");
// print result
    console.log("buffer", buffer)
// return result
    return buffer;
  }

Then with the buffer you can just save the file using new Moralis.File(imageName, imageData);.

More docs:
https://docs.moralis.io/moralis-server/files/files
https://youtu.be/I_wxIshq4WA

Carlos Z

Hello Carlos,
Thanks for your reply. Late yesterday I discovered the fix… I didn’t know about Moralis Code snippets, but saw something about it on one of the YouTube videos, and installed the extension into VSCode.

I tried all the .file. snippets and one of them gave me the solution. It was the passing of the data to the Moralis.File function that I had wrong.

Simply, this works
var canvasElement = cropper.getCroppedCanvas();
var imageData = canvasElement.toDataURL(“image/png”);
var filename = document.getElementById(“name”).value + “.png”;
const imageFile = new Moralis.File(filename, {base64 : imageData});

Thanks again.

1 Like