1

I want to save my canvas data to file using the Tauri fs module.

This is my code, but it didn't work.

const { writeBinaryFile, BaseDirectory } = window.__TAURI__.fs;

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

var grd = ctx.createLinearGradient(0, 0, 200, 0);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");

ctx.fillStyle = grd;
ctx.fillRect(10, 10, 150, 80);

async function IMAGE() {
  await writeBinaryFile('avatar2.png', canvas.toDataURL(), { dir: BaseDirectory.Document });
}

IMAGE()

I have tried to convert DataUrl to other formats, I don't know if it will help or not.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • What does your `package.json` file look like? Are you using [Taurine](https://github.com/Perfect7M/taurine)? It looks like this executes client-side, since you are querying the DOM. – Mr. Polywhirl Jul 13 '23 at 13:46
  • Also, what part of it does not work? Have you debugged or logged anything? – Mr. Polywhirl Jul 13 '23 at 13:50
  • I use cargo package manager, and it work when I try to save text file or Uint8Array. this the error "Unhandled Promise Rejection: ReferenceError: Cannot access uninitialized variable" – SiaVash Moghaddas Jul 13 '23 at 13:59
  • What is unitnialized? Sounds like a null-pointer error on the Rust-side. You need more information. – Mr. Polywhirl Jul 13 '23 at 14:16

1 Answers1

1

You can use this function.

function canvasDataToBinary(canvasData) {
  // Remove the data URL prefix (e.g., 'data:image/png;base64,')
  const data = canvasData.replace(/^data:image\/\w+;base64,/, '');

  // Decode the base64 data into binary format
  const binaryString = atob(data);

  // Create a Uint8Array from the binary string
  const length = binaryString.length;
  const binaryArray = new Uint8Array(length);
  for (let i = 0; i < length; i++) {
    binaryArray[i] = binaryString.charCodeAt(i);
  }

  return binaryArray;
}