我如何将 canvas 内容作为文件放入输入类型文件中

How I put the canvas content as a file in a input type file

经过几个月的示例和答案搜索,我找不到任何适合我的东西。欢迎所有帮助。

系统 --- Woocommerce -- 单个产品页面。

我买了一个插件,可以在你打开时附加一张图片 <form class="cart">。这是在单个产品页面中。

基本上,该插件会在表单中添加一个 <input type ="file">,并允许您按顺序附加图像。我对它很满意,因为它运行良好,并且处理了大量后端工作。

另一方面,我有一个 <canvas>,我需要你在 <input type ="file"> 中加载 <canvas> 内容。完成后,附加组件就可以开始工作了。

所以我的问题是: 如何将 canvas 的内容作为文件放入 <input> 中?

最好还是通过FormData和AJAX发送文件。

但是因为它似乎是供个人使用的,并且您已经有一些可以使用

的东西,您可能可以使用我的 中仍然暴露的 hack。请注意,这仍然仅适用于最新的 Chromium 和 Geckos 浏览器(不支持 Webkit,这意味着不支持 iOS)。

所以一步一步是,

  • 利用你的 canvas.
  • 使用 HTMLCanvasElement.toBlob() 方法将其导出到 Blob。
  • 从这个 Blob
  • 构建一个 File
  • 构建一个 DataTransfer 对象
  • 将文件附加到 DataTransfer 的 items 列表中
  • 将您的 .files 属性 设置为 DataTransfer 的 .files

// draw on the canvas
const canvas = document.createElement( "canvas" );
const ctx = canvas.getContext( "2d" );
ctx.fillStyle = "red";
ctx.fillRect( 20, 20, 260, 110 );

// convert to Blob (async)
canvas.toBlob( (blob) => {
  const file = new File( [ blob ], "mycanvas.png" );
  const dT = new DataTransfer();
  dT.items.add( file );
  document.querySelector( "input" ).files = dT.files;
} );

// to prove the image is there
document.querySelector( "#test" ).onclick = (evt) => {
  const file = document.querySelector( "input" ).files[ 0 ];
  document.body.appendChild( new Image() )
    .src = URL.createObjectURL( file );
};
<form method="POST">
  <input type="file" name="file"><br>
  <button>submit</button> (check your dev tools network panel to see the File is sent)
</form>
<br>
<button id="test">
  load input's content as image
</button>