英文:
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., '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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论