[英]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>
內容。 完成后,附加組件就可以開始工作了。
所以我的問題是:如何將畫布的內容作為文件放在<input>
?
但是因為它似乎是供個人使用的,並且您已經有了使用 <form> 的東西,所以您可能可以使用我的 這個答案中仍然公開的黑客。 請注意,這仍然僅適用於最新的 Chromium 和 Geckos 瀏覽器(不支持 Webkit,這意味着不支持 iOS)。
所以一步一步是,
HTMLCanvasElement.toBlob()
方法將其導出到 Blob。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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.