How to post a canvas element as type file?
I have an image in a canvas element
<canvas id="canvas" width="640" height="480"></canvas>
How to post it back to the server as a <input type=file>
Suggested solution:
< input type=file > does not provide any kind of write access - it is read-only: However you can use ´FormData´ to emulate blob-populated form submissions in JavaScript code
From upload and save screenshot taken from users webcam in django --canvas element to file
How to take the input elements from the <form>
and post them, replacing
the form element with the data in the canvas element?
Background: I captured the image with code from https://davidwalsh.name/browser-camera
because <input type="file" accept="image/*" id="capture" capture="camera">
does not work on some browsers. But the code posted by david walsh looks to work on more browsers.
Code by david walsh:
<!--
Ideally these elements aren't created until it's confirmed that the
client supports video/camera, but for the sake of illustrating the
elements involved, they are created with markup (not JavaScript)
-->
<video id="video" width="640" height="480" autoplay></video>
<button id="snap">Snap Photo</button>
<canvas id="canvas" width="640" height="480"></canvas>
<script>
// Grab elements, create settings, etc.
var video = document.getElementById('video');
// Get access to the camera!
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// Not adding `{ audio: true }` since we only want video now
navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
video.src = window.URL.createObjectURL(stream);
video.play();
});
}
/* Legacy code below: getUserMedia */
else if(navigator.getUserMedia) { // Standard
navigator.getUserMedia({ video: true }, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia({ video: true }, function(stream){
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
} else if(navigator.mozGetUserMedia) { // Mozilla-prefixed
navigator.mozGetUserMedia({ video: true }, function(stream){
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
// Elements for taking the snapshot
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var video = document.getElementById('video');
// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 640, 480);
});
</script>