使用 Tauri 中的 fs 模块将画布数据保存为 png 或 jpg。

huangapple go评论135阅读模式
英文:

Save canvas data as png or jpg in Tauri using fs module

问题

我想使用Tauri fs模块将我的画布数据保存到文件中。

这是我的代码,但它没有工作。

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()

我已经尝试将DataUrl转换为其他格式,我不知道是否会有帮助。

英文:

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.

答案1

得分: 1

你可以使用这个函数。

function canvasDataToBinary(canvasData) {
  // 移除数据URL前缀(例如,'data:image/png;base64,')
  const data = canvasData.replace(/^data:image\/\w+;base64,/, '');

  // 将base64数据解码为二进制格式
  const binaryString = atob(data);

  // 从二进制字符串创建Uint8Array
  const length = binaryString.length;
  const binaryArray = new Uint8Array(length);
  for (let i = 0; i < length; i++) {
    binaryArray[i] = binaryString.charCodeAt(i);
  }

  return binaryArray;
}
英文:

You can use this function.

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

  // 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 &lt; length; i++) {
    binaryArray[i] = binaryString.charCodeAt(i);
  }

  return binaryArray;
}

huangapple
  • 本文由 发表于 2023年7月13日 21:22:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76679845.html
  • canvas
  • javascript
  • node.js-fs
  • save
  • tauri

在Nunjucks模板中访问数组在 :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定