- Canvas要素をFile System Access APIを使いPNGで保存する。
- directoryPickerを使えば、pngの連番が30fpsとかで保存可能。
📝FilePickerを使って、1ファイルごと保存する
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(400, 300);
ctx.stroke();
ctx.fillStyle = "#f00";
ctx.beginPath();
ctx.arc(150, 150, 150, 0, 2 * Math.PI);
ctx.fill();
///////////////////////////////////////////////
//https://stackoverflow.com/questions/72615770/store-canvas-screenshot-to-local-filesystem-with-filesystem-api
c.onclick = ()=>{
console.log("abc")
c.toBlob(async function(result) {
console.log(result);
const options = {
types: [
{
description: 'Images',
accept: {
'image/png': ['.png'],
},
},
],
suggestedName: 'Screenshot.png',
};
imgFileHandle = await window.showSaveFilePicker(options);
console.log("Save File chosen");
const writable = await imgFileHandle.createWritable();
await writable.write(result);
await writable.close();
});
}
📂DirectoryPickerを使って、複数ファイル一気に保存する
var c = document.getElementById("myCanvas");
var btn = document.getElementById("btn");
var ctx = c.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(400, 300);
ctx.stroke();
ctx.fillStyle = "#f00";
ctx.beginPath();
ctx.arc(150, 150, 150, 0, 2 * Math.PI);
ctx.fill();
///////////////////////////////////////////////
let dhandle;
let idx = 0;
btn.onclick = async ()=>{
console.log("ファイル名インクリメントして保存")
if(dhandle==null){
dhandle = await window.showDirectoryPicker()
dhandle.requestPermission({ writable: true })
}
await c.toBlob(async function(result) {
//console.log(result);
let fhandle = await dhandle.getFileHandle('filename'+idx+'.png', { create: true });
idx++;
const writable = await fhandle.createWritable();
await writable.write(result);
await writable.close();
});
}