2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

File System Access APIを使ってCanvasをPNG保存

Last updated at Posted at 2023-02-20
  • 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();          
     
   });
}


2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?